步驟:
1瓢捉、創(chuàng)建一個新的js文件频丘。
2、引入一個空的VUE實(shí)例(新的js文件中)泡态。
import Vue from 'vue'//引入vue實(shí)例
3搂漠、實(shí)例化引入的空實(shí)例(新的js文件中)。
let VueEvent=new Vue();
4某弦、將VueEvent暴露出去(新的js文件中)桐汤。
export default VueEvent;
5、再發(fā)送端和接收端均引入之前實(shí)例化的空Vue實(shí)例靶壮。
6怔毛、痛快地發(fā)送與接收:
代碼:
App.vue:
<template>
<div id="app">
<v-home></v-home>
<v-news></v-news>
<router-view/>
</div>
</template>
<script>
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>
app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
}
</style>
VueEvent.js:
import Vue from 'vue'//引入vue實(shí)例
let VueEvent=new Vue();
export default VueEvent;
Home.vue:
<template>
<div>
<h2>我是一個首頁組件</h2>
<button @click="EmitNews()">給News組件廣播數(shù)據(jù)</button>
</div>
</template>
<script>
import VueEvent from '../model/VueEvent.js';
export default {
name: "home",
data(){
return {
msg:'首頁組件',
title:123,
}
},
methods:{
EmitNews(){//給News組件廣播數(shù)據(jù)
VueEvent.on('to_home',(data)=>{
alert(data)
})
}
}
</script>
<style scoped lang="scss">
h2{
color:red;
}
</style>
News.vue:
<template>
<div>
<h2>我是一個新聞組件</h2>
<button @click="EmitHome()">給Home組件廣播數(shù)據(jù)</button>
</div>
</template>
<script>
import VueEvent from '../model/VueEvent.js';
export default {
name: "news",
data(){
return {
msg:'新聞組件',
}
},
methods:{
EmitHome(){
VueEvent.on('to_news',(data)=>{
alert(data)
})
}
}
</script>
<style scoped>
</style>