vue-component-communication

vue父子组件通信

Vue2.0只能用props从父向子传递消息,以下是实现从子到父传递的方法

前端模板

1
2
3
<input type="text" v-model="message">
<my-component :message="message" @on-change="change"></my-component>
//父组件绑定on-change事件,监听子组件的变化

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var tp = Vue.component('my-component',{
props:['message'],
data:function () {
return{
des:124,
myMessage:this.message
}
},
template:'<div><input v-model="myMessage"></div>',//绑定副本数据
watch:{
message(val){
this.myMessage = val;//创建一个mymessage副本
},
myMessage(val){
this.$emit("on-change",val)//自定义触发事件
}
}
})

父组件

1
2
3
4
5
6
7
8
9
10
11
var vm = new Vue({
el:'#test',
data:{
message:'hello vue.js'
},
methods:{
change:function (val) {
this.message = val;
}
}
})

  1. 在组件内的data对象中创建一个props属性的副本
    因为result不可写,所以需要在data中创建一个副本myResult变量,初始值为props属性result的值,同时在组件内所有需要调用props的地方调用这个data对象myResult。
  2. 创建针对props属性的watch来同步组件外对props的修改
    此时在组件外(父组件)修改了组件的props,会同步到组件内对应的props上,但是不会同步到你刚刚在data对象中创建的那个副本上,所以需要再创建一个针对props属性result的watch(监听),当props修改后对应data中的副本myResult也要同步数据。
  3. 创建针对props副本的watch,通知到组件外
    此时在组件内修改了props的副本myResult,组件外不知道组件内的props状态,所以需要再创建一个针对props副本myResult,即对应data属性的watch。
    在组件内向外层(父组件)发送通知,通知组件内属性变更,然后由外层(父组件)自己来变更他的数据