vue2.0 父子组件通信 兄弟组件通信

父组件是通过props属性给子组件通信的来看下代码:

父组件:

<parent>
    <child :child-com="content"></child> //注意这里用驼峰写法哦
</parent>

data(){
    return {
        content:'sichaoyun'
    };
}

子组件通过props来接受数据

第一种方法

props: ['childCom']

第二种方法

props: {
    childCom: String //这里指定了字符串类型,如果类型不一致会警告的哦
}

第三种方法

props: {
    childCom: {
        type: String,
        default: 'sichaoyun' 
    }
}

子组件与父组件通信

vue2.0只允许单向数据传递,我们通过出发事件来改变组件的数据,废话少说,上干货

子组件代码

<template>
    <div @click="open"></div>
</template>

methods: {
   open() {
        this.$emit('showbox','the msg'); //触发showbox方法,'the msg'为向父组件传递的数据
    }
}

父组件

<child @showbox="toshow" :msg="msg"></child> //监听子组件触发的showbox事件,然后调用toshow方法

methods: {
    toshow(msg) {
        this.msg = msg;
    }
}

兄弟组件之间的通信

我们可以实例化一个vue实例,相当于一个第三方

let vm = new Vue(); //创建一个新实例

组件他哥

<div @click="ge"></div>
methods: {
    ge() {
        vm.$emit('blur','sichaoyun'); //触发事件
    }
}

组件小弟接受大哥命令

<div></div>
created() {
  vm.$on('blur', (arg) => { 
        this.test= arg; // 接收
    });
}

猜你喜欢

转载自blog.csdn.net/qq_31965515/article/details/87921528