非父子组件传值
- 1、新建一个js文件(vueEvent.js) 引入vue 实例化vue 最后暴露这个实例
- 2、在要广播的地方引入刚才定义的实例
- 3、通过 VueEvent.$emit('名称',‘数据’);
- 4、在接受数据的地方 通过$on 接受广播的数据
VueEvent.$on('名称',(data)=>{ console.log(data) })
非父子传值 home组件传给News组件
App.vue
<template> <div id="app"> <router-link to="/">Home</router-link> <v-news></v-news> <router-view /> </div> </template> <script> import news from "./components/News"; import { log } from "util"; export default { components: { "v-news": news //导入news组件 } }; </script> <style> </style>
vueEvent.js
import Vue from 'vue'; var VueEvent = new Vue(); export default VueEvent;
Home.vue
<template> <div class="home"> <div>home组件</div> <button @click="emitHome">给News组件广播数据</button> <div>{{homeMsg}}</div> </div> </template> <script> import VueEvent from "../model/vueEvent"; export default { name: "home", data() { return { msg: "我是home的msg", }; }, mounted() { VueEvent.$on("to-home", data => { this.homeMsg = data;//在news里面 已经把数据给到 to-home ,得到数据后赋值给homeMsg }); }, methods: { emitHome() { VueEvent.$emit("to-news", this.msg); //把home组件的msg传给news.vue } } }; </script>
News.vue
<template> <div id="news"> <div>我是新闻组件</div> <div>{{newss}}</div> <button @click="emitNews()">给home组件广播数据</button> </div> </template> <script> import VueEvent from "../model/vueEvent"; export default { data() { return { msg: "我是一个home组件", newss: "" }; }, mounted() { VueEvent.$on("to-news", data => { this.newss = data; }); }, methods: { emitNews() { VueEvent.$emit("to-home", this.msg);//把数据给到to-home 里面 } } }; </script> <style lang="scss" scoped> </style>
来源:https://www.cnblogs.com/divtab/p/11497984.html