1. bus 总线的方式 (把 bus 定义在 vue 的 prototype 上, 在全局都可以使用)
(1) 在 main.js 中添加如下代码
const Bus = new Vue()
Vue.prototype.$bus = Bus
(2) 在组件中 child1.vue (发送数据端)
<button @click="sendTochild2">发送数据到child2</button>
data() {
return {
child1Data: "我是child1中的数据"
}
},
methods: {
sendTochild2 () {
this.$bus.$emit("getMessage", this.child1Data)
}
}
(2) 在组件中 child2.vue (接收数据端)
create () {
this.$bus.$on("getMessage", this.getchild1sendData)
},
beforDestory () {
this.$bus.$off("getMessage", this.getchild1sendData)
},
methods: {
getchild1sendData (data) {
console.log(data)
}
}
2. props 和 $emit
(2.1) 父组件向子组件传值, 在父组件 parent.vue 中
<child :user="user"></child>
data () {
return {
user: [1, 2, 3, 4, 5]
}
}
(2.2) 在子组件 child.vue 中
props: {
user: {
type: Array,
required: true,
default: () => {
return [2, 2, 2]
},
validator: (val) => {
return val.includes(4)
}
}
}
(2.3) 子组件向父组件传值 (通过事件形式), 在组件 child.vue 中
<button @click="sendToParent">发送数据到父组件</button>
methods: {
sendToParent () {
this.$emit("sendToParent", "我是子组件中的数据")
}
}
(2.4) 在父组件 parent.vue 中
<child @sendToParent="sendToParent"></child>
methods: {
sendToParent (data) {
console.log(data)
}
}
3. provide/ inject
(3.1) 在 A.vue 组件中
provide () {
return {
info: this.info,
getData: this.getData
}
},
data () {
return {
info: "我是祖先中的数据"
}
},
methods: {
getData () {
console.log("我是祖先中的事件")
}
}
(3.2) 在 C.vue 组件中使用
inject: ["info", "getData"]
或者:
inject: {
c1: {
from: "info",
default: ""
},
C2: {
from: "getData"
}
}