vue父子,兄弟组件之间的传值通信

vue中组件之间通讯分为三种: 父传子、子传父、兄弟组件之间的通讯

1. 父组件给子组件传值:

父组件可以使用props向子组件传递数据

父组件模板:

<template>
    <child :msg="message"></child>
</template>

<script>
import child from './child.vue';
export default {
    components: {
        child
    },
    data () {
        return {
            message: 'father data';
        }
    }
}
</script>

子组件模板:

<template>
    <div>{{msg}}</div>
</template>

<script>
export default {
    props: {
        msg: {
            type: String,
            required: true
        }
    }
}
</script>

2. 子组件向父组件通信
父组件向子组件传递事件方法,子组件通过$emit触发事件,回调给父组件。

父组件模板:

<template>
    <child @Func="func"></child>
</template>

<script>
import child from './child.vue';
export default {
    components: {
        child
    },
    methods: {
        func (msg) {
            console.log(msg);
        }
    }
}
</script>

子组件模板:

<template>
    <button @click="handleClick">点我</button>
</template>

<script>
export default {
    props: {
        msg: {
            type: String,
            required: true
        }
    },
    methods () {
        handleClick () {
            this.$emit('Func');
        }
    }
}

3. 兄弟组件之间通信

父子组件中可以用props$emit()。那么怎么实现非父子组件间的通信,可以通过实例一个vue brother作为媒介,要相互通信的兄弟组件之中,都引入brother,然后通过分别调用brother事件触发和监听来实现通信和参数传递。 brother.js可以是这样写:

import Vue from 'vue'
export default new Vue()

在需要通信的组件都引入brother.js

<template>
	<button @click="toBrother">子组件传给兄弟组件</button>
</template>

<script>
import Bus from '../common/js/brother.js'
export default{
	methods: {
	    toBrother() {
	        Bus.$emit('on', '来自兄弟组件')
	    }
	  }
}
</script>

另一个组件也import brother.jsmounted钩子函数中监听on事件:

import Bus from '../common/js/brother.js'
export default {
    data() {
      return {
        message: ''
      }
    },
    mounted() {
       Bus.$on('on', (msg) => {
         this.message = msg
       })
     }
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值