vue $emit $on 非父子非兄弟组件传值
bus.js 放置src根目录
import Vue from 'vue' export default new Vue()
test1.vue 传值组件
<template> <div> <button @click="add()">点击</button> </div> </template> <script> import Bus from '../bus.js' export default { data () { return { msg: 'I come from first' } }, methods: { add () { // 定义add方法,并将msg通过txt传给test2组件 Bus.$emit('txt', this.msg) this.$router.push({name: 'test2'}) this.msg = '' } } } </script> <style scoped> </style>
test2.vue 接收组件 console.log(_this.msg) 打印出test1 传过来的值
<template>
<div>{{msg}}</div>
</template>
<script>
import Bus from '../bus.js'
export default {
data () {
return {
foo: 'Foo component',
msg: 'I come from second'
}
},
mounted: function () {
let _this = this
Bus.$on('txt', function (msg) {
_this.msg = msg
console.log(_this.msg)
})
}
}
</script>
<style scoped>
</style>

浙公网安备 33010602011771号