import Vue from "vue";
var VueEvent=new Vue()
export default VueEvent;
<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:'首页组件'
}
},
methods:{
// 广播数据
emitNews(){
VueEvent.$emit('to-news',this.msg)
}
},
components:{
}
}
</script>
<style lang="scss" scoped>
h2{
color: red;
}
</style>
<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>
<template>
<div id="app">
<h2>{{msg}}</h2>
<v-home></v-home>
<br>
<hr>
<v-news></v-news>
</div>
</template>
<script>
// 非父子组件之间传值
// 1.新建一个js文件,然后引入vue,实例化vue,最后暴露这个实例
// 2.在要广播的地方引入刚才暴露的实例
// 3.通过VueEvent.$emit('名称','数据')
// 4.在接收数据的地方,通过VueEvent.$on('名称',function('数据'){})
import Home from './components/Home.vue';
import News from './components/News.vue';
export default {
name: 'app',
data () {
return {
msg:'根组件'
}
},
methods:{
},
components:{
'v-home':Home,
'v-news':News
}
}
</script>
<style>
</style>