组件之间的通信分为2种
父组件向子组件传数据
<div id="app">div> <script>// 子组件 Vue.component('Child',{ template:`<p>我是子组件,接收到父组件传来的数据:{{msg}}</p>`, //{{ }}使用数据 props:['msg'] //在props中用msg属性|变量来接收父组件传来的数据 }) // 父组件 Vue.component('Parent',{ template:`<div><p>我是父组件</p><child msg='hello'></child> </div> ` }) new Vue({ el:'#app', template:`<parent></parent>` //使用父组件 }); script>
如果要传递多个数据,使用多个属性即可。
子组件向父组件传数据
<div id="app">div> <script>// 子组件 Vue.component('Child',{ template:`<div><p>我是子组件</p> @click='sendToParent',表示这个元素发生click事件时,就调用sendToParent()方法 --><button @click='sendToParent'>发送数据给父组件</button> </div>`, methods:{ sendToParent(){this.$emit("received","hello"); //this.$emit("自定义的事件名",数据),表示当前组件触发指定事件,这个事件会携带指定的数据 } } }) // 父组件 Vue.component('Parent',{ template:`<div><p>我是父组件,这是子组件传来的数据:{{msg}}</p> 使用子组件。发生received事件时,使用指定的方法来处理 --><child @received="receivedFromChild"></child> </div> `, data(){return{ msg:''} }, methods:{ receivedFromChild(val){ //使用一个参数来接收数据this.msg=val; //将数据赋给data中的msg变量 } } }) new Vue({ el:'#app', template:`<parent></parent>` //使用父组件 }); script>
说明
<div id="app">div> <script>// 子组件 Vue.component('Child',{ template:`<div><p>我是子组件</p>发送时可以带参数--><button @click='sendToParent("chy",20)'>发送数据给父组件</button></div>`, methods:{ sendToParent(val1,val2){ //对应的函数自然要声明参数this.$emit("received",val1,val2); //可以带0个、1个、多个数据,带多个时逗号分隔即可。这些数据可以使用传进来的参数、表单字段的值等 } } }) // 父组件 Vue.component('Parent',{ template:`<div><p>我是父组件,这是子组件传来的数据:{{msg1}} {{msg2}}</p> 注意:接收时不能带参数表,带参数表反而会出错 --><child @received="receivedFromChild"></child> </div> `, data(){return{ msg1:'', msg2:''} }, methods:{ receivedFromChild(val1,val2){ //传来几个数据,就用几个参数接收this.msg1=val1; this.msg2=val2; } } }) new Vue({ el:'#app', template:`<parent></parent>` }); script>
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4