常规方法
父组件使用v-bind给子组件传值,子组件使用props接收
父组件
<template>
<Children v-bind:attr="value" />
</template>
子组件
props: [ "attr" ]
或者
props: {
attr: {
// 对所接受值的限制
}
}
如果对接收的值没有限制,props可以写成一个数组,如果对所接受的值有限制,比如必传、类型、默认值等props需要写成一个对象,为接受的值做各种限制
子传父
子组件给父组件传值时,子组件使用$emit发射一个事件,父组件监听这个事件来获得子组件传来的值
子组件
methods: {
passValue() {
this.$emit("eventName", "我是子组件传给父组件的值");
}
}
父组件
<template>
<Children @eventName="acceptValue"/>
</template>
methods: {
acceptValue(value) {
// value的值为 "我是子组件传给父组件的值"
}
}
父组件和可以通过ref来获取和修改子组件的值
父组件
<template>
<Children ref="child"/>
</template>
methods: {
getChildValue() {
this.$refs.child.attr // 获取子组件attr的值
this.$refs.child.attr = "newValue" // 修改子组件attr的值
}
}
Bus
bus可以用在任何组件之间的传值
首先在main.js中添加以下代码
Vue.prototype.$bus = new Vue();
使用方式
需要传值的的组件
methods: {
passValue() {
this.$bus.$emit("eventName", "bus传的值")
}
}
接收值得组件
create() {
this.$bus.$on("eventName", value => {
// value的值为 "bus传的值"
})
}
传值的组件触发this.$bus.$emit("eventName", "bus传的值")事件时, 接收值得组件会触发this.$bus.$on("eventName", () => {})的回调函数
provide/inject
使用
父组件
provide() {
return {
attr: this.value // this.的方式传递当前组件内的值
}
},
子组件
inject: ["attr"] // 通过this.的方式使用
注意:传的值如果是对象,那么它是响应式的,传的字符串则不是响应式的
如果父组件和子组件同时provide的相同名字的值,则孙组件取子组件的值
总结:
直接父子组件使用常规方法给子组件传值比较方便,兄弟组件使用Bus比较方便,层级很深的组件之间传值使用provide/injec比较方便,关系特别复杂的组件传值借助vuex是最明智的选择