Vue component communication classification and solutions, please give examples

Communication between Vue components

Communication between Vue components can be divided into the following categories:

Parent-child component communication

The parent component passes data to the child component through props, and the child component sends messages to the parent component through the event $emit.

These two methods are the most commonly used ways to implement parent-child communication.

This parent-child communication method is a typical one-way data flow . The parent component passes data through props. The child component cannot directly modify the props, but must inform the parent component to modify the data by sending events.

In addition, these two methods can also be directly implemented using the syntactic sugar v-model, because v-model will be parsed into a prop named value and an event named input by default.

This method of syntax sugar is a typical two-way binding, often used on UI controls, but ultimately, it still allows the parent component to modify data through events.

Of course, we can also access the methods and data in the component instance through the access $parentor object .$children

Sample code:

   // Parent.vue
   <template>
     <div>
       <Child :message="message" @update="handleUpdate" />
     </div>
   </template>

   <script>
   import Child from './Child.vue';

   export default {
     data() {
       return {
         message: 'Hello, child component!'
       }
     },
     methods: {
       handleUpdate(newMessage) {
         this.message = newMessage;
       }
     },
     components: {
       Child
     }
   }
   </script>

   // Child.vue
   <template>
     <div>
       <p>{
   
   { message }}</p>
       <button @click="sendMessage">Send Message</button>
     </div>
   </template>

   <script>
   export default {
     props: ['message'],
     methods: {
       sendMessage() {
         this.$emit('update', 'New message from child component!');
       }
     }
   }
   </script>

Sibling component communication

Use a shared Vue instance or event bus for communication between sibling components.

This situation can be achieved by searching for the child components in the parent component. That is
this.$parent.$children, in $children, you can query the required component instance through the component name and then communicate.

Sample code:

   // EventBus.js
   import Vue from 'vue';
   export const EventBus = new Vue();

   // ComponentA.vue
   <template>
     <div>
       <button @click="sendMessage">Send Message to Component B</button>
     </div>
   </template>

   <script>
   import { EventBus } from './EventBus.js';

   export default {
     methods: {
       sendMessage() {
         EventBus.$emit('message', 'Hello, Component B!');
       }
     }
   }
   </script>

   // ComponentB.vue
   <template>
     <div>
       <p>{
   
   { message }}</p>
     </div>
   </template>

   <script>
   import { EventBus } from './EventBus.js';

   export default {
     data() {
       return {
         message: ''
       }
     },
     mounted() {
       EventBus.$on('message', (msg) => {
         this.message = msg;
       });
     }
   }
   </script>

Communicate across multiple layers of components

For this situation, you can use the new API provide / inject in Vue 2.2 . Although the document does not recommend using it directly in business, it is still very useful if used well.

Using Vuex for component communication

Vuex is the state management library officially provided by Vue, which can share and modify data between different components.

Sample code:

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    
    
  state: {
    
    
    message: 'Hello, Vuex!'
  },
  mutations: {
    
    
    updateMessage(state, newMessage) {
    
    
      state.message = newMessage;
    }
  },
  actions: {
    
    
    updateMessage({
     
      commit }, newMessage) {
    
    
      commit('updateMessage', newMessage);
    }
  }
});

// ComponentA.vue
<template>
  <div>
    <p>{
    
    {
    
     message }}</p>
    <button @click="sendMessage">Send Message to Component B</button>
  </div>
</template>

<script>
import {
    
     mapActions, mapState } from 'vuex';

export default {
    
    
  computed: {
    
    
    ...mapState(['message'])
  },
  methods: {
    
    
    ...mapActions(['updateMessage']),
    sendMessage() {
    
    
      this.updateMessage('New message from Component A!');
    }
  }
}
</script>

// ComponentB.vue
<template>
  <div>
    <p>{
    
    {
    
     message }}</p>
  </div>
</template>

<script>
import {
    
     mapState } from 'vuex';

export default {
    
    
  computed: {
    
    
    ...mapState(['message'])
  }
}
</script>

These are several classifications and solutions for communication between Vue components. You can choose the appropriate method for inter-component communication according to actual needs.

For more details, please search " " on WeChat前端爱好者 and click me to view .

The ultimate solution to all communication problems

As long as you are not afraid of trouble, you can use Vuex or Event Bus to solve all the above communication situations.

Expand

Why is there one-way data flow in vue?

The reason for using one-way data flow in Vue is to ensure the traceability and maintainability of data , and to reduce the side effects caused by data changes .

Here are some of the benefits of Vue adopting unidirectional data flow:

  1. Easy to understand: In the one-way data flow model, data can only be passed from the parent component to the child component through props, and in the child component, data can only be returned to the parent component through event triggering. This clear direction of data flow makes the code easier to understand and debug.

  2. Responsive update: The one-way data flow model allows Vue to better track data changes and automatically update the view. When data changes, Vue will detect the change and update related components to ensure synchronization of data and views.

  3. Data predictability: The one-way data flow model makes the flow of data clearly visible. Each component can only modify its own data and will not directly modify the data of other components. This restriction ensures data predictability and reduces potential data conflicts and errors.

  4. Component independence: Since data can only be communicated through props passing and event triggering, dependencies between components are more clear and isolated. This makes components more independent, reusable, and easier to unit test and maintain.

Although the one-way data flow model has some limitations, it can meet the needs of front-end development in the vast majority of cases and brings better maintainability and predictability.

If you need to share state between different components or implement more complex data flow management, you can use specialized state management libraries such as Vuex to assist.

One-way data flow and two-way data binding in vue

One-way data flow and two-way data binding in Vue are two important concepts of Vue.

  1. One-way data flow: In Vue, the data flow is one-way, that is, data can only flow from the parent component to the sub-component, and the sub-component cannot directly modify the data of the parent component. It can only be indirect by triggering the function passed by the parent component. Implement modifications. This data flow method can ensure the controllability of data, prevent child components from making arbitrary modifications to the data of parent components, and also reduce the difficulty of debugging.

  2. Two-way data binding: In Vue, data binding is two-way, that is, when the data changes, the view will also be updated, and when the view changes, the data will also be updated. This two-way binding mechanism can achieve real-time synchronization of views and data, making it easier for developers to interact with user interfaces and data.

In Vue, two-way data binding can be achieved using v-model. The v-model directive can bind the value of the form element to the data of the Vue instance. When the user enters content in the form element, the data of the Vue instance will also be updated accordingly. At the same time, when the data of the Vue instance changes, the form elements will also be updated accordingly.

In short, one-way data flow and two-way data binding are two core concepts of Vue, which together constitute Vue's efficient data-driven view mechanism.

Guess you like

Origin blog.csdn.net/BradenHan/article/details/135007143