注释很详细,直接上代码
上一篇
新增内容
- 媒介js的创建
- 发送组件发送事件示例
- 接收组件接收事件示例
源码
App.vue
<template><div id="app"><TessFirst></TessFirst><TestSecond></TestSecond></div>
</template>
<script>javascript">
import TessFirst from "./components/TestFirst.vue";
import TestSecond from "./components/TestSecond.vue";
export default {name: "App",components: {TessFirst,TestSecond},data() {return {};},methods: {},
};
</script>
<style>
</style>
bus.js
import Vue from 'vue'
// 创建一个空的vue实例
export default new Vue()
TestFirst.vue
<template><div>发送组件:<input type="text" v-model="sendMessage" @input="handleChange" /></div>
</template>
<script>javascript">
//以bus为桥梁
import bus from "../bus.js";
export default {data() {return {sendMessage: "",};},methods: {//发送消息handleChange(e) {//向bus发送方法与数据bus.$emit("getMessage", e.target.value);},}
};
</script><style lang="less" scoped></style>
TestSecond.vue
<template><div>接收组件的值:{{ getMessage }}</div>
</template><script>javascript">
//以bus为媒介接收订阅事件
import bus from "../bus.js";
export default {data() {return {getMessage: "",};},created() {//监听事件,接收订阅事件并渲染bus.$on("getMessage", (val) => {this.getMessage = val;});}
};
</script><style lang="scss" scoped></style>
效果演示