子组件Content向App.vue通工自定义事件传值
App.vue
<script>import Content from "./components/Content.vue";export default { data() { return { message: '', }; }, methods:{ getChildMsg:function (value){ console.log(value); this.message=value } }, components:{ Content }}</script><template><div> <!--拿到子组件 Content 的msg数据 --> <!--在父组件通过v-on监听自定义的子组件的自定义事件 --> <Content @injectMsg="getChildMsg"> </Content> <h2>{{message}}</h2></div></template>
- Content.vue
<template> <div> <!--组件是能够复用 --> <Hello_kugou :message="msg" :static='56'></Hello_kugou> <h3>{{msg}}</h3> <button @click="msg='酷狗'"> chagebut</button> <button @click="sendParent">提交数据给父组件</button> </div></template><script>const obj={ msg:"hello---kugou"}import Hello_kugou from "./Hello_kugou.vue";export default { data(){//让每一个组件对象都返回一个对象,不对数据净化 return{ msg: 'hellokugoumsg', list: [1,2,3] }; }, components:{ Hello_kugou }, methods:{ // 在子组件理 $emit 触发事件 sendParent:function (){ //this.$emit('事件名称', '发送的事件参数') this.$emit('injectMsg', this.msg) } }, name: "Content"}</script><style scoped></style>
- Hello_kugou.vue
<template> <div> <h2>hello kugou</h2> <h2>{{message2}}--调用父组件的变量</h2> </div></template><script>export default { name: "Hello_kugou", //props: ['message', 'static'] props:{ // message: String,//类型限度 // static: String message2:{ type:String, default:"nihhaokugou", //required:true }, }}</script><style scoped></style>