SoFunction
Updated on 2025-04-05

Summary of various flexible data transmission methods in Vue3

Preface, Understanding Vue 3 Data Stream

Vue 3 provides a variety of data transfer methods, allowing our components to communicate with each other. Next, let’s take a look at how these methods work.

1. Props: The classic path from father to son

In Vue, subcomponents can be passedpropsReceiving data passed by the parent component is an old tradition of passing data from the parent component to the child component. This is like parents giving their children pocket money. Children can only use what their parents give and cannot get the money from their families by themselves.

// Parent component<template>
  <ChildComponent :message="greeting" />
</template>

<script setup>
import ChildComponent from './';

const greeting = 'Hello!';
</script>

// Subcomponents<script setup>
const props = defineProps({
  message: String,
});
(message); // "Hello!"
</script>

<script setup>The Composition API is used, which simplifies how props are accessed. So we don't need to passpropsObjects to access the value of prop, you can declare prop as a variable directly and use it in templates or logic.

2. Emits: The call of subcomponents

If a child component needs some data, you can't wait for the parent component to pass it. So thenEmits, it allows subcomponents to transmit signals upward. passdefineEmitsand$emit, the child component can tell the parent component: "I have something to notify!"

// Parent component&lt;template&gt;
  &lt;ChildComponent @updateMessage="newGreeting = $event" /&gt;
  &lt;p&gt;{{ newGreeting }}&lt;/p&gt;
&lt;/template&gt;

&lt;script setup&gt;
import ChildComponent from './';
let newGreeting = '';
&lt;/script&gt;

// Subcomponents&lt;script setup&gt;
const emit = defineEmits(['updateMessage']);
const updateParent = () =&gt; {
  emit('updateMessage', 'Updated from child!');
};
&lt;/script&gt;

The parent component contains a child component instance and listens to the child component's issuance.updateMessageevent. When this event is fired, the parent component will update its internalnewGreetingData properties.

A method is defined in a child componentupdateParent, when this method is called, it will fireupdateMessageevent and pass a string as parameter to the parent component.

Whenever triggeredupdateMessageEvent, the parent component will receive this event and update itnewGreetingThe value of , thus displaying the updated message on the page.

here,$eventIt is just a conventional variable name that is used to capture event objects or data passed by events in the event processor. Usually in order to make the code easier to read and understand, we will choose the appropriate variable name based on the actual content of the event data.

3. Provide / inject: communication in the context

Sometimes components are nested deep, such as child components in the parent component and grand components in the child component... When the component level is very deep, or data needs to be shared across multiple components,provideandinjectIt comes in handy. They allow us to pass data freely in the component tree without having to pass props layer by layer. This is very useful when dealing with deeply nested components.

// Parent component&lt;script setup&gt;
import { provide } from 'vue';
provide('theme', 'dark');
&lt;/script&gt;

// Subsidiary components&lt;script setup&gt;
import { inject } from 'vue';
const theme = inject('theme');
(theme); // "dark"
&lt;/script&gt;

In the parent component, we useprovidefunction to provide a name'theme'key and corresponding value'dark'. This makes'theme'Can be accessed by all its child components and their child components.

In the descendants component, you useinjectFunction to obtain'theme'The value of the key.injectThe function will look for the most recent ancestor component provided by the'theme'The value that the key matches.

wheninjectWhen called, Vue looks up along the component tree until a provider matching the injection key is found. If a matching provider is not found,injectWill returnundefined. To avoid this, it caninjectProvides a default value.

const theme = inject('theme', 'light'); // If no provider is found, use 'light' as the default value

Although provide / inject avoids the cumbersomeness of having to pass props between components on each layer, overuse of this approach may lead to increased coupling between components, making the code difficult to track and maintain, so it is recommended to use it appropriately.

4. Vuex: Expert in global state management

Since providing / inject is not easy to overuse, let’s talk about Vuex now, which is ideal for handling global state in complex applications. With Vuex, we can easily manage state across components.

1. Install Vuex

If Vuex has not been installed, just npm.

npm install vuex

2. Create the Vuex Store

First, you need to create a Vuex store file.

import { createStore } from 'vuex';

export default createStore({
  state: {
    theme: 'light',
  },
  mutations: {
    setTheme(state, theme) {
       = theme;
    },
  },
  actions: {
    changeTheme({ commit }, theme) {
      commit('setTheme', theme);
    },
  },
  getters: {
    currentTheme(state) {
      return ;
    },
  },
});
  • stateis the store's data container.

  • mutationsis the only way to submit to the store, they are responsible for modifying the state.

  • actionsIt is a processing function for asynchronous operations and can contain any asynchronous operation logic.

  • gettersIs a computed property of the store, used to obtain the derived state of the state from the store.

3. Use Vuex Store in the main application file

In our main application file, import and use the Vuex store.

import { createApp } from 'vue';
import App from './';
import store from './store';

const app = createApp(App);
(store);
('#app');

4. Use Vuex Store in Components

Use the properties and methods of the store directly.

&lt;template&gt;
  &lt;div :class="theme"&gt;
    &lt;!-- use getter --&gt;
    &lt;p&gt;The current theme is {{ currentTheme }}.&lt;/p&gt;
    &lt;!-- use action --&gt;
    &lt;button @click="changeTheme('dark')"&gt;Switch to dark theme&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script setup&gt;
import { computed, onMounted } from 'vue';
import { useStore } from 'vuex';

const store = useStore();

const theme = computed(() =&gt; );
const currentTheme = computed(() =&gt; );

function changeTheme(newTheme) {
  ('changeTheme', newTheme);
}

onMounted(() =&gt; {
  ('Current theme:', );
});
&lt;/script&gt;
  • themeandcurrentThemeIt is usedcomputedThe responsive references created are mapped to the status and getter of the store respectively.

  • changeThemeFunction useCome to triggerchangeThemeaction, parameters are the new topic value.

  • onMountedThe hook ensures execution immediately after the component is mounted and is used to check and record the current topic.

When the topic changes in the Vuex store,themeandcurrentThemeResponsive features, components automatically update the UI to reflect new topics.changeThemeThe function provides the function of switching themes, and can trigger changes to the theme by clicking a button.

In addition to vuex, there is also a pinia that is similar to it, so I won't introduce it here.

Conclusion

At this point, we explored the colorful data transmission methods in Vue 3, from basic Props and Emits, to advanced Provide and Inject, and Vuex for global state management. Each method has its own unique application scenarios, it depends on how we choose.

The above is the detailed content of various flexible data transmission methods in Vue3. For more information about Vue3’s data transmission methods, please pay attention to my other related articles!