1

一.父传子组件通信

clipboard.png

拿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'
    })
}


a2774206
1.8k 声望26 粉丝

You can't forget your role at all times