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.js
在mounted
钩子函数中监听on事件:
import Bus from '../common/js/brother.js'
export default {
data() {
return {
message: ''
}
},
mounted() {
Bus.$on('on', (msg) => {
this.message = msg
})
}
}