bus.js 放置src根目录vue
import Vue from 'vue' export default new Vue()
test1.vue 传值组件this
<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 传过来的值spa
<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>