Home Web Front-end Vue.js Comparison of multi-level delivery schemes in Vue component communication

Comparison of multi-level delivery schemes in Vue component communication

Jul 18, 2023 pm 03:21 PM
emit provide/inject prop

Comparison of multi-level delivery schemes in Vue component communication

Vue is a very popular front-end framework. It provides a component-based development method, through the nesting and communication of components. development of complex applications. In actual development, communication between components is often an important issue. When there are multi-level relationships between components, how to efficiently transfer data becomes a question that developers need to think about. This article will introduce several common multi-level component communication schemes and compare them.

  1. Using props and $emit

Vue provides two methods, props and $emit, to implement data transfer between parent and child components. Props are used by parent components to pass data to child components, and child components obtain data through props. $emit is used by child components to pass data to parent components. The parent component obtains data by listening to the $emit event on child components.

The sample code is as follows:

Parent component:

<template>
  <child-component :message="message" @update-message="updateMessage"></child-component>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  data() {
    return {
      message: ''
    }
  },
  components: {
    ChildComponent
  },
  methods: {
    updateMessage(newMessage) {
      this.message = newMessage
    }
  }
}
</script>
Copy after login

Child component:

<template>
  <button @click="sendMessage">发送消息</button>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      default: ''
    }
  },
  methods: {
    sendMessage() {
      this.$emit('update-message', 'Hello, Vue!')
    }
  }
}
</script>
Copy after login

This solution is suitable for communication between parent and child components, but when When there are multi-level relationships between components, props and $emit need to be continuously passed among the intermediate components, and the code will become complex and difficult to maintain.

  1. Using Event Bus

Event Bus is a global event bus that implements communication between components by creating a global Vue instance. The component listens for events through $on and triggers events through $emit.

The sample code is as follows:

EventBus.js:

import Vue from 'vue'
export default new Vue()
Copy after login

Parent component:

<template>
  <child-component></child-component>
</template>

<script>
import ChildComponent from './ChildComponent.vue'
import EventBus from './EventBus.js'

export default {
  components: {
    ChildComponent
  },
  mounted() {
    EventBus.$on('update-message', (newMessage) => {
      this.message = newMessage
    })
  }
}
</script>
Copy after login

Child component:

<template>
  <button @click="sendMessage">发送消息</button>
</template>

<script>
import EventBus from './EventBus.js'

export default {
  methods: {
    sendMessage() {
      EventBus.$emit('update-message', 'Hello, Vue!')
    }
  }
}
</script>
Copy after login

Use Event Bus Communication between any components can be achieved, but because it is a global event bus, naming conflicts and event confusion are prone to occur. And because components communicate directly through events, it is unintuitive and difficult to track.

  1. Using Vuex

Vuex is Vue’s official state management library, used to implement shared state between components. In Vuex, data is stored in a centralized store, and components change the data by calling store methods.

The sample code is as follows:

store.js:

import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    message: ''
  },
  mutations: {
    updateMessage(state, newMessage) {
      state.message = newMessage
    }
  }
})
Copy after login

Parent component:

<template>
  <child-component></child-component>
</template>

<script>
import ChildComponent from './ChildComponent.vue'
import store from './store.js'

export default {
  components: {
    ChildComponent
  },
  computed: {
    message() {
      return this.$store.state.message
    }
  }
}
</script>
Copy after login

Child component:

<template>
  <button @click="sendMessage">发送消息</button>
</template>

<script>
import store from './store.js'

export default {
  methods: {
    sendMessage() {
      this.$store.commit('updateMessage', 'Hello, Vue!')
    }
  }
}
</script>
Copy after login

Using Vuex can It solves the problem of communication between components very well, especially suitable for components with multi-level relationships. However, because data needs to be transferred through the store, the store needs to be introduced into the component and the data changed through the commit method, which relatively increases the complexity of the code.

To sum up, the multi-level delivery solutions in Vue component communication include props and $emit, Event Bus and Vuex. Depending on the actual situation, choosing an appropriate solution can better improve development efficiency and code maintainability.

The above is the detailed content of Comparison of multi-level delivery schemes in Vue component communication. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve '[Vue warn]: Missing required prop' error How to solve '[Vue warn]: Missing required prop' error Aug 26, 2023 pm 06:57 PM

How to solve the "[Vuewarn]:Missingrequiredprop" error When developing Vue applications, you sometimes encounter a common error message: "[Vuewarn]:Missingrequiredprop". This error usually refers to the lack of required property values ​​in the component, causing the component to fail to render properly. The solution to this problem is simple. We can avoid and deal with this error through some skills and regulations. Here are some solutions

How to use props and emit in Vue3 How to use props and emit in Vue3 May 26, 2023 pm 06:13 PM

Function: The parent component passes data down to the child component through props; Purpose: When a type of component needs to be used multiple times, each call is only different in specific places, just like a personal profile form, which needs to be filled out each time. The information is different for each person, but the structure is the same. Usage 1 (simple acceptance without specifying the type): Introduce the subcomponent into the parent component, pass the parameters through the label attribute of the subcomponent, and define a props option in the subcomponent for reception and use. Note that there is no need to add props in the subcomponent. Other places are defined in advance above. You can see that the age passed in is a string type. If you want the passed in value to be automatically increased by 1, you cannot add 1 when using the subcomponent. As shown in the figure below, it will become a string.

How to solve the '[Vue warn]: Invalid prop: invalid value' error How to solve the '[Vue warn]: Invalid prop: invalid value' error Aug 25, 2023 pm 02:51 PM

Methods to solve "[Vuewarn]:Invalidprop:invalidvalue" error When developing applications using Vue.js, we often encounter some errors and warnings. One of the common errors is "[Vuewarn]:Invalidprop:invalidvalue". This error usually occurs when we try to pass an invalid value to a property of a Vue component. In this article, we will delve into the root cause of this error

How to solve '[Vue warn]: Invalid prop: type check' error How to solve '[Vue warn]: Invalid prop: type check' error Aug 26, 2023 pm 10:40 PM

How to Fix “[Vuewarn]:Invalidprop:typecheck” Error Vue.js is a popular JavaScript framework for building user interfaces. When developing applications using Vue.js, we sometimes encounter some error messages, one of which is "[Vuewarn]:Invalidprop:typecheck". This error is usually caused by incorrect use of attributes in the component

How to solve the '[Vue warn]: Invalid prop: custom validator' error How to solve the '[Vue warn]: Invalid prop: custom validator' error Aug 20, 2023 pm 10:53 PM

Methods to solve the "[Vuewarn]:Invalidprop:customvalidator" error During the development process of using Vue, we often encounter some warning and error messages. One of the common error messages is "[Vuewarn]:Invalidprop:customvalidator". The reason this error message occurs is because when we use the custom validator function, we fail to correctly validate the component passed to it.

How to solve the '[Vue warn]: Avoid mutating a prop directly' error How to solve the '[Vue warn]: Avoid mutating a prop directly' error Aug 17, 2023 pm 05:21 PM

Methods to solve the "[Vuewarn]:Avoidmutatingapropdirectly" error When developing projects using Vue.js, we may encounter a common warning message: "[Vuewarn]:Avoidmutatingapropdirectly". The meaning of this warning message is that we should not directly change the value of a props attribute, but should trigger an event to let the parent component change the pro

How to deal with '[Vue warn]: Avoid mutating a prop directly' error How to deal with '[Vue warn]: Avoid mutating a prop directly' error Aug 17, 2023 am 11:12 AM

How to deal with "[Vuewarn]:Avoidmutatingapropdirectly" error When developing web applications using Vue.js, we often encounter some warnings or errors. One of the common warnings is "[Vuewarn]:Avoidmutatingapropdirectly", which means that we directly modify a property (prop) passed by the parent component in the component. In this article, we

How to solve the '[Vue warn]: Invalid prop: update value' error How to solve the '[Vue warn]: Invalid prop: update value' error Aug 26, 2023 pm 08:19 PM

Methods to solve the "[Vuewarn]:Invalidprop:updatevalue" error In Vue development, we often encounter the "[Vuewarn]:Invalidprop:updatevalue" error. This error is usually caused by a parent component passing an invalid value to a child component. Although this error is a Vue warning rather than a fatal error, it should still be resolved in time to ensure the robustness of the program. This article will introduce

See all articles