核心提示:一.创建 input.vue 添加如下代码:Input Component组件' type='text' v-model='message' />发送消息scriptexport default {n...
一.创建 input.vue 添加如下代码:
Input Component
组件" type="text" v-model="message" /> <script> export default { name: "inputCom", data() { return { message: "" }; }, methods: { sendMessage(val) { // 事件名字自定义,用不同的名字区别事件 this.$root.bus.$emit("changeMsg", this.message); } } }; </script>
二.创建dialog.vue 添加如下代码:
Dialog Component
Receive Message From Input Component:{{InputMessage}}
<script> export default { name: "dialogCom", data() { return { message: "hello input", InputMessage: "未收到消息", active: "MessageNo" }; }, mounted() { this.$root.bus.$on("changeMsg", Value => { this.print(Value); }); }, methods: { print(Value) { this.InputMessage = Value; } }, beforeDestroy() { this.$root.bus.$off("changeMsg"); }, computed: { classObject() { return { isReceived: this.InputMessage == "未收到消息" ? true : false }; } }, watch: { InputMessage: function() { console.log(this.active); this.active = this.InputMessage == "未收到消息" ? "MessageNo" : "MessageOk"; } } }; </script>
三.创建nonParentChildCommunication.vue 文件添加如下代码:
非父子组件通信
以下实现步骤:
- 1.在 main.js 中 添加data属性
- 2.添加需要通信的非父子组件(项目中实现的步骤)
- 2.1:创建 input.vue
- 2.2创建 dialog.vue
- 2.3:nonParentChildCommunication.vue
以下是效果:
<script> import Input from "./input"; import Dialog from "./dialog"; export default { name: "nonParentChildcommunication", data() { return { mainJSCode: ` new Vue({ el: '#app', data() { return { bus: new Vue() // 给data添加一个 名字为eventHub 的空vue实例,用来传输非父子组件的数据 } }, router, components: { App }, template: '', }).$mount('#app'); // 手动挂载,#app `, inputCode: ` template:
Input Component!
script: export default { name: "inputCom", data() { return { message: "" }; }, methods: { sendMessage(val) { // 事件名字自定义,用不同的名字区别事件 this.$root.bus.$emit("changeMsg", this.message); } } }; `, dialogCode: ` template:
Dialog Component!
Input Component Transmit Message:{{InputMessage}}
script: export default { name: "dialogCom", data() { return { message: "hello input", InputMessage: "" }; }, mounted() { this.$root.bus.$on("changeMsg", Value => { this.print(Value); }); }, methods: { print(Value) { this.InputMessage = Value; } }, beforeDestroy() { this.$root.bus.$off("changeMsg"); } }; `, nonParentChildCommCode: ` template: Input>
script: import Input from "./input"; import Dialog from "./dialog"; export default{ components: { Input, Dialog } } ` }; }, methods: {}, components: { Input, Dialog } }; </script>
如果 不是特别清楚 请 下载 完整项目自己跑下就清楚了
注意: src/components/Non-parent-childComponentsCommunicate下的文件为非父子组件通信