Home Web Front-end Vue.js Detailed explanation of the use of state manager Vuex 4 in Vue 3 to achieve global data sharing

Detailed explanation of the use of state manager Vuex 4 in Vue 3 to achieve global data sharing

Sep 11, 2023 pm 12:24 PM
vue state manager Global data sharing

Vue 3中的状态管理器Vuex 4使用详解,实现全局数据共享

Vue 3 is a popular JavaScript framework commonly used for building user interfaces. It can be easily combined with the state manager Vuex for global data sharing. This article will delve into the use of Vuex 4, the new version in Vue 3, to help developers better understand and apply this powerful state management tool.

First, we need to install Vuex 4. In a Vue 3 project, you can use the npm or yarn command to install the latest version of Vuex.

npm install vuex@next

or

yarn add vuex@next

After the installation is complete, import the Vuex module in the entry file of Vue 3 and use the createApp function to create a Vue application instance.

import { createApp } from 'vue'
import { createStore } from 'vuex'
import App from './App.vue'

const store = createStore({
  // 这里定义Vuex的状态和操作
})

const app = createApp(App)
app.use(store)
app.mount('#app')

In the above code, we use the createStore function to create a Vuex store instance and use it as a plug-in to use Vuex for state management throughout the application.

Next, let us understand the two most important concepts in Vuex 4: state and operation (mutation).

State is a data source in the application and can be accessed in any component. Operations are methods used to modify state. They change state in a synchronous manner. In Vuex 4, states and operations are defined using pure functions.

For example, we can define a counter state and an increment operation in Vuex.

const store = createStore({
  state() {
    return {
      counter: 0
    }
  },
  mutations: {
    increment(state) {
      state.counter++
    }
  }
})

In the above code, we define an initial state counter is 0, and define an operation named increment, which can be passed state.counter to increment the counter value.

Using Vuex states and operations in components is very simple. State and operations can be accessed through the $store object.

export default {
  methods: {
    incrementCounter() {
      this.$store.commit('increment')
    }
  },
  computed: {
    counter() {
      return this.$store.state.counter
    }
  }
}

In the above code, we trigger the increment operation through the commit method, and use the state method to obtain the counterThe current value of the status.

In addition to states and operations, Vuex 4 also introduces new features: actions and getters.

Actions are functions that operate on state asynchronously. In Vuex 4, actions can be defined through the actions attribute.

const store = createStore({
  state() {
    return {
      counter: 0
    }
  },
  mutations: {
    increment(state) {
      state.counter++
    }
  },
  actions: {
    asyncIncrement({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  }
})

In the above code, we define an action named asyncIncrement, which simulates asynchronous operations through the setTimeout function and triggers after 1 secondincrementOperation.

Getter is a computed property used to obtain status. In Vuex 4, getters can be defined through the getters attribute.

const store = createStore({
  state() {
    return {
      counter: 0
    }
  },
  mutations: {
    increment(state) {
      state.counter++
    }
  },
  getters: {
    doubleCounter(state) {
      return state.counter * 2
    }
  }
})

In the above code, we define a getter named doubleCounter, which returns double the counter status.

Using actions and getters in components is similar to using operations and states. Actions can be triggered through the $store.dispatch method, and getter values ​​can be obtained through the $store.getters property.

export default {
  methods: {
    asyncIncrement() {
      this.$store.dispatch('asyncIncrement')
    }
  },
  computed: {
    counter() {
      return this.$store.state.counter
    },
    doubleCounter() {
      return this.$store.getters.doubleCounter
    }
  }
}

In the above code, we trigger the asyncIncrement action through the this.$store.dispatch method, and pass the this.$store.getters. doubleCounter to get the value of doubleCounter.

To summarize, Vuex 4 provides a convenient way to manage global data sharing in Vue 3 applications. By defining states, operations, actions and getters, we can easily share and manage data. I hope this article will help you better understand the usage and principles of Vuex 4.

The above is the detailed content of Detailed explanation of the use of state manager Vuex 4 in Vue 3 to achieve global data sharing. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Article

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 add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

Netflix's Frontend: Examples and Applications of React (or Vue) Netflix's Frontend: Examples and Applications of React (or Vue) Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

React, Vue, and the Future of Netflix's Frontend React, Vue, and the Future of Netflix's Frontend Apr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vue How to implement component jump for vue Apr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

How to develop a complete Python Web application? How to develop a complete Python Web application? May 23, 2025 pm 10:39 PM

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

See all articles