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>