Sons assembly between a non-traditional values
1. Create a new file VueEvent.js in src / model directory
View import from "views" ; var VueEvent = new View () export default VueEvent;
2. In the src / components assembly Home.vue new directory and News.vue
Home.vue
<template> <div> <h2>{{msg}}</h2> <br> <button @click="emitNews()">给News组件广播数据</button> <br> </div> </template> <script> import VueEvent from "../model/VueEvent.js" export default { name: 'home', data () { return { MSG: ' Home assembly ' } }, Methods: { // broadcast data emitNews () { VueEvent $ EMIT (. ' to-News ' , the this a .msg) } }, Components: { } } </ Script > < style lang = "SCSS" scoped > H2 { Color : Red ; } </ style >
News.vue
<template> <div> <h2>{{msg}}</h2> </div> </template> <script> import VueEvent from "../model/VueEvent.js" export default { name: 'home', data () { return { msg:'新闻组件' } }, methods:{ }, components:{ }, mounted(){ VueEvent.$on('to-news',function(data){ console.log(data) }) } } </script> <style lang="scss" scoped> h2{ color: red; } </style>
3. In the App.vue
< Template > < div ID = "App" > < H2 > {{MSG}} </ H2 > < V-Home > </ V-Home > < br > < HR > < V-News > </ V-News > </ div > </ Template > < Script > // pass values between the non-parent-child assembly // 1. Create a js file, and then introduced into the VUE, VUE instantiated, the instance of the last exposure @ 2 to be broadcast in just place the introduction of the exposed examples // 3. by VueEvent. $ emit ( 'Name ',' data ') //4. Where the reception data by VueEvent $ on ( 'name', function ( 'Data') {}). Import from Home ' ./components/Home.vue ' ; Import from News ' ./components/News. VUE ' ; Export default { name: ' App ' , Data () { return { MSG: ' root component ' } }, Methods: { }, components: { ' V-Home ' : Home, ' V-News ' : News } } </script> <style> </style>