1. Create a new bus.js
Import View from 'for' export default new view
2. vue value documents pass and receive values, each incorporated bus.js
import bus from '../util/bus'
3. The method defined by value using a bus. $ Emit ( 'methodName', data), methodName method custom name
<button @click="trans()">传值</button>
methods: { trans(){ bus.$emit('test',this.helloData) } },
4. In the assembly to receive the values, the use bus.on ( 'methodName', val => {}), val is the value pass over the
mounted(){ bus.$on('test',val=>{ console.log(val); this.cdata = val }) }
Complete example:
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 View from 'for' export default new view
Subassemblies 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>
Subassemblies 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>