1.新建bus.js
import Vue from 'vue'
export default new Vue
知识兔2.在需要传值和接受值的vue文件中,各自引入bus.js
import bus from '../util/bus'
知识兔3.定义传值的方法,使用bus.$emit('methodName',data), methodName是自定义的方法名
<button @click="trans()">传值</button>
知识兔methods: {
trans(){
bus.$emit('test',this.helloData)
}
},
知识兔4.在要接收值的组件里,使用bus.on('methodName',val =>{ }) ,val 就是传过来的值
mounted(){
bus.$on('test',val=>{
console.log(val);
this.cdata = val
})
}
知识兔完整例子:
App.vue
<template>
<div id="app">
<HelloWorld/>
<child></child>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
import Child from './components/Child'
export default {
name: 'App',
components: {
HelloWorld,Child
}
}
</script>
知识兔bus.js
import Vue from 'vue'
export default new Vue
知识兔子组件HelloWorld.vue
<template>
<div>
<button @click="trans()">传值</button>
</div>
</template>
<script>
import bus from '../util/bus'
export default {
name: "HelloWorld",
data () {
return {
helloData:"hello"
};
},
methods: {
trans(){
bus.$emit('test',this.helloData)
}
},
}
</script>
知识兔子组件Child.vue
<template>
<div>
{{cdata}}
</div>
</template>
<script>
import bus from '../util/bus'
export default {
name: "Child",
data () {
return {
cdata:"子数据"
};
},
mounted(){
bus.$on('test',val=>{
console.log(val);
this.cdata = val
})
}
}
</script>
知识兔