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 passedprops
Receiving 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 passprops
Objects 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. passdefineEmits
and$emit
, the child component can tell the parent component: "I have something to notify!"
// Parent component<template> <ChildComponent @updateMessage="newGreeting = $event" /> <p>{{ newGreeting }}</p> </template> <script setup> import ChildComponent from './'; let newGreeting = ''; </script> // Subcomponents<script setup> const emit = defineEmits(['updateMessage']); const updateParent = () => { emit('updateMessage', 'Updated from child!'); }; </script>
The parent component contains a child component instance and listens to the child component's issuance.updateMessage
event. When this event is fired, the parent component will update its internalnewGreeting
Data properties.
A method is defined in a child componentupdateParent
, when this method is called, it will fireupdateMessage
event and pass a string as parameter to the parent component.
Whenever triggeredupdateMessage
Event, the parent component will receive this event and update itnewGreeting
The value of , thus displaying the updated message on the page.
here,
$event
It 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,provide
andinject
It 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<script setup> import { provide } from 'vue'; provide('theme', 'dark'); </script> // Subsidiary components<script setup> import { inject } from 'vue'; const theme = inject('theme'); (theme); // "dark" </script>
In the parent component, we useprovide
function 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 useinject
Function to obtain'theme'
The value of the key.inject
The function will look for the most recent ancestor component provided by the'theme'
The value that the key matches.
wheninject
When called, Vue looks up along the component tree until a provider matching the injection key is found. If a matching provider is not found,inject
Will returnundefined
. To avoid this, it caninject
Provides 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 ; }, }, });
state
is the store's data container.mutations
is the only way to submit to the store, they are responsible for modifying the state.actions
It is a processing function for asynchronous operations and can contain any asynchronous operation logic.getters
Is 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.
<template> <div :class="theme"> <!-- use getter --> <p>The current theme is {{ currentTheme }}.</p> <!-- use action --> <button @click="changeTheme('dark')">Switch to dark theme</button> </div> </template> <script setup> import { computed, onMounted } from 'vue'; import { useStore } from 'vuex'; const store = useStore(); const theme = computed(() => ); const currentTheme = computed(() => ); function changeTheme(newTheme) { ('changeTheme', newTheme); } onMounted(() => { ('Current theme:', ); }); </script>
theme
andcurrentTheme
It is usedcomputed
The responsive references created are mapped to the status and getter of the store respectively.changeTheme
Function useCome to trigger
changeTheme
action, parameters are the new topic value.onMounted
The 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,theme
andcurrentTheme
Responsive features, components automatically update the UI to reflect new topics.changeTheme
The 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!