在vue-cli中组件通信的方法

2020-06-16 06:13:21易采站长站整理

本文介绍了在vue-cli中组件通信的方法,分享给大家。具体如下:

vue组件之间的通信包括三种:

1.父组件向子组件通信
2.子组件向父组件通信
3.同级组件之间的通信

一.父传子组件通信

拿app.vue当父组件,content.vue当子组件

1.父组件中导入子组件(子组件导出)


import contents from './components/content';

2.在父组件中注册子组件


data() {
return {
test:'0'
};
},
components:{
'v-header':headers,
'v-content':contents
}

3.子组件通过props来接收数据


<v-content :childs='test'></v-content>

二.子与父组件通信

子组件:


<template>
<div @click="down()"></div>
</template>

methods: {
down() {
this.$emit('down','null'); //主动触发down方法,'null'为向父组件传递的数据
}
}

父组件:


<div>
<child @down="changes" :test="test"></child> //监听子组件触发的down事件,然后调用changes方法
</div>
methods: {
changes(msg) {
this.test= test;
}
}

二.非父子组件通信


//把a当作一个中转站
var a = new Vue();

组件1触发:


<div @click="eve"></div>
methods:{
eve(){
a.$emit("change",'null')
}
}

组件2接收:


<div></div>
created(){
a.$on('change',()=>{
this.msg = 'null'
})
}