1.新建VueEvent.js,创建实例
import Vue from 'vue'
var VueEvent =new Vue()
export default VueEvent;
2.在需要传值的组件中引入实例
import VueEvent from "../model/VueEvent.js";
3.通过VueEvent.$emit获取对方的数据
4.在本组件中通过VueEvent.$on进行监听
代码:
第一个组件
<template>
<div>
<div>我是第一个组件</div>
<button @click="Second()">aaa</button>
</div>
</template>
<script>
import VueEvent from "../model/VueEvent.js";
export default {
data() {
return {
msg: "我是aaa"
}
},
methods: {
Second() {
VueEvent.$emit("to-bbb", this.msg);
}
},
mounted() {
VueEvent.$on("to-aaa", function(data) {
console.log(data);
});
}
};
</script>
<style scoped>
</style>
第二个组件
<template>
<div>
<div>我是第二个组件</div>
<button @click="First()">bbb</button>
</div>
</template>
<script>
import VueEvent from "../model/VueEvent.js";
export default {
data() {
return {
msg: "我是bbb"
}
},
methods: {
First() {
VueEvent.$emit("to-aaa", this.msg);
}
},
mounted() {
VueEvent.$on("to-bbb", function(data) {
console.log(data);
});
}
};
</script>
<style scoped>
</style>
在主页挂载它们就可以显示:
<template>
<div id="app">
<!-- <v-home></v-home> -->
<v-first></v-first>
<hr />
<v-second></v-second>
</div>
</template>
<script>
//引入组件
//import a from './components/father.vue';
import aaa from "./components/aaa.vue";
import bbb from "./components/bbb.vue";
export default {
name: "App",
data() {
return{}
},
components: {
// 'v-home':a , //挂载组件;
"v-first": aaa,
"v-second": bbb
}
};
</script>
<style>
</style>
结果: