详解vue2.0组件通信各种情况总结与实例分析

2020-06-12 21:14:57易采站长站整理

</div>
<script>
var userPf=Vue.component('user-profile',{
template:'<div>hello $refs</div>'
});
var parent = new Vue({ el: '#parent' });
// 访问子组件
var child = parent.$refs.profile;
console.log(child[0]);
console.log(parent.$refs.p);
</script>

$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅作为一个直接访问子组件的应急方案——应当避免在模版或计算属性中使用 $refs 。

数据反传—自定义事件

自定义事件的根基在于每个vue实例都实现了事件接口(Event interface)

Vue的事件系统分离自浏览器的EventTarget API。尽管它们的运行类似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的别名。

 父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件

监听:$on(eventName)
触发:$emit(eventName)


<div id="app3">
<p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
<child v-on:add="pChange"></child>
<child v-on:add="pChange"></child>
<child v-on:click.native="native"></child>
</div>
<script>
Vue.component('child', {
template: `<button @click="add">{{ c }}</button>`,
data: function () {
return {
c: 0,
msg: 'I am from child's data'
}
},
methods: {
add: function () {
this.c += 1;
this.$emit('add',this.msg);
}
},
});
new Vue({
el: '#app3',
data: {
t: 0,
childWords: ''
},
methods: {
pChange: function (msg) {
this.t += 1;
this.childWords=msg;
},
native:function () {
alert('I am a native event ,which comes from the root element!');
}
}
})
</script>

兄弟间通信—简单场景用bus,复杂场景用vuex


<div id="app4">
<display></display>
<increment></increment>
</div>
<script>
var bus = new Vue();
Vue.component('increment', {
template: `<button @click="add">+</button>`,
data: function () {
return {count: 0}
},
methods: {
add: function () {
bus.$emit('inc', this.count+=1)
}
}
});
Vue.component('display', {
template: `<span>Clicked: <mark>{{c}}</mark> times</span>`,
data: function () {
return {c: 0}
},
created: function () {
var self=this;