您的位置:首页 > 产品设计 > UI/UE

vue 组件之间的通信(父子、非父子)

2018-01-09 17:48 841 查看
//子组件向父组件传递数据
<div id="app">
<test-child receive-child="标题"></test-child>
</div>

- 在子组件test-child使用 props 声明: props:['receiveChild']
然后父组件就可以向trans里传递数据,动态数据需加冒号 :receive-child="fathermsg"

- 为 prop 指定验证规则,如果传入的数据不符合要求,Vue 会发出警告。
props:{
'recStr':{
type:String,    //类型不要加引号
default:"我是默认字符串"
}
'recArr':{
type:Array,
default:function(){    //数组和对象需用函数返回数据
return ["第1项","第2项","第3项"]
}
}
}


//子组件向父组件传递数据:
<div id="app">
{{showMsg}}
<test-child @send="getChild"></test-child>
</div>

- 在子组件的HTML里定义一个触发事件:
<li @click="sendMsg">点击我触发</li>
- 在子组件的methods:
sendMsg:function(ev){
this.$emit('send',ev.target.innerHtml)  //send是自定义事件,后面的是参数
}
- 在父组件的methods里:
getChild:function(str){
this.showMsg=str    //showMsg在父组件的data里定义
}


//非父子组件间的通信:
<div id="app">
<test-header></test-header>
<test-list></test-list>
</div>
- 空实例方法:
$emit   //发布
$on    //订阅
///////////////////////////////////////
//list向header传递数据:
- 定义一个空实例:
var busVm = new Vue();

- 在list组件里定义一个触发事件:
<li @click="sendMsg">点击我触发</li>

- 在list组件的methods发布:
sendMsg:function(ev){
busVm.$emit('send',123)  //send是自定义事件,后面的是参数

- 在header组件的mounted里订阅:
mounthe:function(){
busVm.$on('send',function(num){
console.log(num);
}.bind(this))
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: