非父子组件传值
通过事件广播实现非父子组件传值
1.新建js,引入并实例化Vue
import Vue from 'vue'
var VueEvent = new Vue();
export default VueEvent;
2.子组件A中引入VueEvent,并广播事件
import VueEvent from '../model/VueEvent.js'
VueEvent.$emit('to-news',this.msg);
3.子组件B中引入VueEvent,并监听事件
import VueEvent from '../model/VueEvent.js'
VueEvent.$on('to-news',data=>{console.log(data);});
示例代码
import Vue from 'vue' var VueEvent = new Vue(); export default VueEvent;
<template> <div id="home"> <button @click="sendMsg()">我来触发事件</button> </div> </template> <script> import VueEvent from "../models/VueEvent.js"; export default { data() { return { msg: "我是Home的msg" }; }, methods: { sendMsg() { VueEvent.$emit("tonews", this.msg); } } }; </script> <style> </style>
<template> <div id="news"> 我来接受事件--{{msg}} </div> </template> <script> import VueEvent from "../models/VueEvent.js"; export default { data() { return { msg: "我是News的msg" }; }, mounted() { VueEvent.$on("tonews", res => { this.msg = res; }); } }; </script> <style> </style>
<template> <div id="app"> <v-home></v-home> <hr /> <v-news></v-news> </div> </template> <script> import Home from "./components/Home.vue"; import News from "./components/News.vue"; export default { name: "app", data() { return { msg: "Welcome to Your Vue.js App" }; }, components: { "v-home": Home, "v-news": News } }; </script> <style lang="scss"> </style>