Home >Web Front-end >Vue.js >How to communicate between non-parent-child components in vue2.0?

How to communicate between non-parent-child components in vue2.0?

青灯夜游
青灯夜游forward
2020-11-05 18:02:111982browse

The following Vue.js tutorial column will introduce to you the communication method between vue2.0 non-parent-child components. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to communicate between non-parent-child components in vue2.0?

In vue, the parent component uses props to communicate with its component, and the child component uses the $emit event to communicate with the parent component. So what about communication between parent and child? , there are only a few strokes in the official document, the concept of

is very vague, where should this empty vue instance be placed? There is no clear description in the optical release document. After checking some other information, I found that this non-father-son communication is actually used like this:

First of all, this empty instance needs to be placed under the root component, so that all sub-components can call it, that is, placed in main .js below, as shown in the figure:

import Vue from 'vue'
import App from './App'
import router from './router'


Vue.config.productionTip = false;


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  data:{
    Hub:new Vue()
  },
  template: &#39;<App/>&#39;,
  components: { App }
});

My two components are called child1.vue and child2.vue. Now I want to click the button in child1.vue to change the value in child2.vue. At this time we need to use a $root tool to achieve:

child1.vue:

<template lang="pug">
  p this is child
    span(@click="correspond") 点击进行非组件之间的通信
</template>
<script>
  export default{
    methods: {
      correspond(){
          this.$root.Hub.$emit("change","改变")
      }

    }
  }
</script>

child2.vue:

<template lang="pug">
  p this is child2
    span {{message}}
</template>
<script>
  export default{
    data(){
      return {
        message: "初始值"
      }
    },
    created(){
      this.$root.Hub.$on("change", () => {
        this.message = "改变"
      })
    }
  }
</script>

At this point we can achieve what we want The effect.

Related recommendations:

2020 front-end vue interview questions summary (with answers)

vue tutorial Recommendation: The latest 5 vue.js video tutorial selections in 2020

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to communicate between non-parent-child components in vue2.0?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete