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>
分类:
vue / vue3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理