12:vue3 组件事件(子传父 )
1、触发与监听事件(子传父this.$emit)
Parent.vue
1 <template> 2 <h3>Parent父组件</h3> 3 <Child @parentEvent="parentEventHandle"></Child> 4 <p>子组件传递的数据:{{ message }}</p> 5 <p>userInfo:{{ userInfo }}</p> 6 <p>name={{ name }}, age={{ age }}</p> 7 </template> 8 9 <script> 10 import Child from './Child.vue'; 11 export default{ 12 data(){ 13 return{ 14 message:"", 15 userInfo:"", 16 name:"", 17 age:0 18 } 19 }, 20 components:{ 21 Child 22 }, 23 methods: { 24 parentEventHandle(data1,data2){ 25 this.message=data1; 26 this.userInfo=data2; 27 this.name=data2.name; 28 this.age=data2.age; 29 } 30 } 31 } 32 </script>
child.vue
1 <template> 2 <h3>Child子组件</h3> 3 <button @click="clickEventHandle">传递数据到父组件</button> 4 </template> 5 6 <script> 7 export default{ 8 data(){ 9 return{ 10 msg:"child数据", 11 userInfo:{ 12 name:"amy", 13 age:20 14 } 15 } 16 }, 17 methods:{ 18 clickEventHandle(){ 19 this.$emit("parentEvent",this.msg,this.userInfo) 20 } 21 } 22 } 23 </script>
2、组件事件配合 v-model 使用
Parent.vue
1 <template> 2 <h3>Parent父组件</h3> 3 <Child @parentEvent="parentEventHandle"></Child> 4 <p>父组件显示搜索结果:{{ searchValue }}</p> 5 </template> 6 7 <script> 8 import Child from './Child.vue'; 9 export default{ 10 data(){ 11 return{ 12 searchValue:"" 13 } 14 }, 15 components:{ 16 Child 17 }, 18 methods: { 19 parentEventHandle(data){ 20 this.searchValue=data; 21 } 22 } 23 } 24 </script>
Child.vue
1 <template> 2 <h3>Child子组件</h3> 3 <input type="text" v-model="searchKey"/> 4 </template> 5 6 <script> 7 export default{ 8 data(){ 9 return{ 10 searchKey:"" 11 } 12 },
//侦听器 13 watch:{ 14 searchKey(newValue,oldValue){ 15 this.$emit("parentEvent",newValue); 16 } 17 } 18 } 19 </script>
3、通过函数使用Props实现子传父
1 <template> 2 <h3>Parent父组件</h3> 3 <Child title="父元素传递的值" :onEvent="dataFn"></Child> 4 <p>父组件显示:{{ message }}</p> 5 </template> 6 7 <script> 8 import Child from './Child.vue'; 9 export default{ 10 data(){ 11 return{ 12 message:"" 13 } 14 }, 15 components:{ 16 Child 17 }, 18 methods: { 19 dataFn(data){ 20 this.message=data; 21 } 22 } 23 } 24 </script>
1 <template> 2 <h3>Child子组件</h3> 3 <p>子组件显示:{{ title }}</p> 4 <p>{{ onEvent("来自子元素传递的数据") }}</p> 5 </template> 6 7 <script> 8 export default{ 9 data(){ 10 return{ 11 12 } 13 }, 14 props:{ 15 title:String, 16 onEvent:Function 17 } 18 } 19 </script>