1.新建bus.js
import Vue from 'vue'
export default new Vue
2.在需要传值和接受值的vue文件中,各自引入bus.js
import bus from '../../../utils/bus' // 在src目录的下面
3.定义传值的方法,使用bus.$emit(‘methodName’,data)
4.要接收值的组件里,使用bus.on(‘methodName’,val =>{ })
5 具体示例如下所示
index.vue
<template>
<div>
<Child1></Child1>
<Child2></Child2>
</div>
</template>
<script>
import Child1 from './module/child1'
import Child2 from './module/child2'
export default {
components: {
Child1,
Child2
}
}
</script>
child1.vue
<template>
<div>
<button @click="trans()">传值</button>
</div>
</template>
<script>
import bus from '../../../utils/bus'
export default {
name: "Child1",
data() {
return {
helloData: "hello"
};
},
methods: {
trans() {
bus.$emit('test', this.helloData) // 传值
}
},
}
</script>
child2.vue
<template>
<div>
{{cdata}}
</div>
</template>
<script>
import bus from '../../../utils/bus'
export default {
name: "Child2",
data() {
return {
cdata: "子数据"
};
},
mounted() {
bus.$on('test', val => { // 接收值
console.log(val);
this.cdata = val
})
}
}
</script>