vuejs中组件之间的数据传递
1.将全局数据传递至子组件中(先将数据从实例对象的全局传递至父组件,再将父组件数据传递到子组件)
//.html
<father :fr="fr"【第一步:首先将实例的全局变量传递到父组件的属性中】></father>
//js-father控件
Vue.component('father',{
props:["fr"],【第二部:将该父控件的属性值写入props数组中表明要在子控件中使用】
template: "<ul><li v-for='fr_item in fr'>{{fr_item}}</li></ul>"
});
//js-实例化vue对象
new Vue({
el: "#app",
data: {
fr:[
{name:"常见"},
{name:"张嘴"}
]
}
});
2.将子组件中的数据传递至父组件中
<father :fr="fr" @change-num="handle($event)" :num="num"></father>【第二步,因为触发子控件事件导致父控件自定义事件触发,触发事件函数,将子控件传输的数据传输给该函数,注意:固定要给其参数为$event】
//js-father控件
Vue.component('father',{
props:["fr","num"],
template: "<ul><li v-for='(fr_item,index) in fr' @click='$emit(\'change-num\',index)'【第一步,首先触发事件,用$emit(自定义事件,需要传递的值)传递】>{{fr_item}}</li></ul>{{num}}"
});
//js-实例化vue对象
new Vue({
el: "#app",
data: {
num:0,
fr:[
{name:"常见"},
{name:"张嘴"}
]
},
methods: {
handle: function(val){
this.num=val;
}
}
});
3.兄弟组件之间的数据传输