首页 / VUE / vue组件间通信子与父详解(二)
vue组件间通信子与父详解(二)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了vue组件间通信子与父详解(二),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2548字,纯文字阅读大概需要4分钟。
内容图文
![vue组件间通信子与父详解(二)](/upload/InfoBanner/zyjiaocheng/340/40b66de0a0a549108ceb62da501d93f6.jpg)
接着vue组件父与子通信详解继续学习。
二、组件间通信(子组件传值给父组件)
通过事件的方式来完成数据的传输。
①在父组件中 定义一个方法,用来接收子组件所通过事件传来的值
methods:{ recvMsg:function(msg){ //参数msg就是子组件通过事件出来的数据 } }
②绑定事件处理函数
事件一般情况 都是自定义事件
<child-component @myEvent="recvMsg"></child-component>
③在子组件触发事件
事件名,值 this.$emit('myEvent',myPhone) //触发一个叫做myEvent的事件,同时把第二个参数数据传递给事件对应的处理函数
总结:
在Vue 中,父子组件的关系可以总结为 props down, events up。父组件通过 props 向下传递数据给子组件,子组件通过 events 给父组件发送消息。
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>组件间通信子传父</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <parent-component></parent-component> </div> <script> //通过事件的方式传递 // 绑定 -- 触发 Vue.component("parent-component",{ data:function(){ return { sonMsg:"" } }, methods:{ //msg参数要拿子传递的值 recvMsg:function(msg){ console.log("父组件接收到子组件的数据"+msg); this.sonMsg = msg; } }, template:` <div> <h1>这是父组件</h1> <p>子组件传来的数据为:{{sonMsg}}</p> <hr/> <child-component @customEvent="recvMsg"></child-component> </div> ` }) Vue.component("child-component",{ methods:{ sendMsg:function(){ //来触发绑定给子组件的自定义方法 //this.$emit("customEvent");第一个参数触发 //this.$emit("customEvent");第二个参数传值 this.$emit("customEvent","哈哈哈哈"); }, }, template:` <div> <h1>这是子组件</h1> <button @click="sendMsg">senToFather</button> </div> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
在子组件中放上一个input,点击按钮 把用户输入的内容发给父组件
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>子与父之间的通信</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <parent-component></parent-component> </div> <script> //创建父组件 Vue.component("parent-component",{ //data属性 data:function(){ return{ sonMsg:"" } }, methods:{ recvMsg:function(msg){ this.sonMsg = msg } }, template:` <div> <h1>父组件</h1> <h4>子组件传递的数据:{{sonMsg}}</h4> <child-component @customEvent="recvMsg"></child-component> </div> ` }) //创建子组件 Vue.component("child-component",{ data:function(){ return { myInput:"" } }, methods:{ sendMsg:function(){ this.$emit("customEvent",this.myInput); } }, template:` <div> <h1>子组件</h1> <input type="text" v-model="myInput"/> <button @click="sendMsg">发送</button> </div> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
内容总结
以上是互联网集市为您收集整理的vue组件间通信子与父详解(二)全部内容,希望文章能够帮你解决vue组件间通信子与父详解(二)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。