您现在的位置:首页 >> 前端 >> 内容

Vue组件通信(非父子组件通信)

时间:2018/7/5 15:09:13 点击:

  核心提示:一.创建 input.vue 添加如下代码:Input Component组件' type='text' v-model='message' />发送消息scriptexport default {n...

一.创建 input.vue 添加如下代码:


<script>
export default {
  name: "inputCom",
  data() {
    return {
      message: ""
    };
  },
  methods: {
    sendMessage(val) {
      // 事件名字自定义,用不同的名字区别事件
      this.$root.bus.$emit("changeMsg", this.message);
    }
  }
};
</script>

二.创建dialog.vue 添加如下代码:


<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 文件添加如下代码:

 <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下的文件为非父子组件通信

Tags:VU UE E组 组件 
作者:网络 来源:bianliuzhu