Home > Web Front-end > Vue.js > body text

How to use Vuex for data management and state sharing?

WBOY
Release: 2023-06-25 13:44:36
Original
1570 people have browsed it

Vuex is a state management library specially designed for Vue.js. It can help us simplify data transfer and management between components and improve the maintainability and scalability of the application. This article will introduce how to use Vuex for data management and state sharing, hoping to help everyone better understand and apply Vuex.

1. What is Vuex?

Vuex is the state management library officially provided by Vue.js. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure state consistency. In Vuex, we can manage our data and state through store. Store contains the following core concepts:

  • state: state data, used to store various state values ​​in the application ;
  • getter: read calculated attributes, used to derive some state values ​​from the store;
  • mutation: synchronously modify the state, used to synchronously modify the data in the state;
  • action: asynchronous modification status, used to process asynchronous operations and submit mutations;
  • module: modularization, used to split large stores into smaller sub-modules and manage them separately status and operations.

2. Why do you need Vuex?

In Vue.js applications, as the component level continues to increase, the data and state transfer between components will become more and more complex. At this time, we need a state management library to help We manage and share various state values ​​across our applications. Using Vuex can bring the following benefits:

  1. Centralized management of state: Each component can access the same state tree, making state management more unified and centralized;
  2. Easy to Maintenance and debugging: Vuex can help us better understand the status and data flow of the application, making debugging and maintenance more convenient;
  3. Improving the readability and maintainability of the code: Using Vuex, you can Concentrate the control flow of data in one place, making the code logic clearer and easier to maintain;
  4. Separate business logic and state management: By storing the state in the Vuex store, you can implement business logic components and state management components Separation facilitates maintenance and management.

3. How to use Vuex?

Before using Vuex, you need to install the Vuex library and introduce it into the Vue project:

npm install vuex --save

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

Vue.use(Vuex)
Copy after login

Next, we need to create a Vuex store and register it in the Vue instance, as follows:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    }
  },
  actions: {
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)
    }
  },
  getters: {
    evenOrOdd(state) {
      return state.count % 2 === 0 ? 'even' : 'odd'
    }
  }
})

new Vue({
  el: '#app',
  store,
  computed: {
    count() {
      return this.$store.state.count
    },
    evenOrOdd() {
      return this.$store.getters.evenOrOdd
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment')
    },
    decrement() {
      this.$store.commit('decrement')
    },
    incrementAsync() {
      this.$store.dispatch('incrementAsync')
    }
  }
})
Copy after login

In the above code, we created a Vuex store containing three core concepts (state, mutations and actions). Among them, state is used to store state data, mutations are used to modify the state synchronously, and actions are used to handle asynchronous operations and submit mutations. Here, we also define a getter that calculates whether the count value in state is even or odd.

In the Vue instance, we use the computed attribute and methods attribute to achieve access to the state, mutation and action in the store. count and evenOrOdd in the computed attribute are calculated based on the actual data in the state, while increment, decrement and incrementAsync in the methods attribute are methods used to modify the state.

4. The use of state and mutation

State is a core concept of Vuex. It is used to store various state values ​​in the application. Generally, it needs to be modified through mutation. In Vuex, we can access and modify state in the following ways:

  1. Access state: We can access state in the store through this.$store.state, as in the sample code above The count in is a state.
  2. Directly modify state:
    Directly modifying state will cause the Vuex static analysis tool to report an error, because the principle of Vuex is that data changes in the store must go through mutations. If we have to modify the state value directly, we need to use Vue.set so that the modification can trigger UI updates responsively. The sample code is as follows:
Vue.set(state.obj, 'newProp', 123)
Copy after login
  1. Modify state through mutation:
    Mutations are a collection of states used to modify, which is a synchronous operation in Vuex. By executing mutations, we can arbitrarily modify the values ​​in the state. Mutations are the only way to modify state in Vuex. Asynchronous operations or other side effects cannot be performed in mutations. We can submit mutations in the following ways:
this.$store.commit('increment')   // 传入 mutation 的名称
this.$store.commit({
  type: 'increment',
  amount: 10    // 传入额外的参数
})
Copy after login

4. Use of actions and getters

In applications, sometimes we need to perform some asynchronous operations. In this case In this case, we can use actions to handle it. Actions can contain any asynchronous operations. Finally, we need to submit mutations to modify the data in the state. In Vuex, we can operate actions in the following ways:

  1. Define action:
actions: {
  incrementAsync(context) {
    setTimeout(() => {
      context.commit('increment')
    }, 1000)
  }
}
Copy after login
  1. Submit action:
this.$store.dispatch('incrementAsync')
Copy after login

In Vuex, getters can be regarded as calculated properties in the store. They are some state values ​​derived from the state of the store, and can cache a large number of repeated and logically complex calculations. In Vuex, we can use getters in the following ways:

  1. Define getter:
getters: {
  evenOrOdd(state) {
    return state.count % 2 === 0 ? 'even' : 'odd'
  }
}
Copy after login
  1. Access getter:
this.$store.getters.evenOrOdd
Copy after login

5. Use of module

在 Vuex 中,如果我们的应用程序中存在大量的 state 和 mutations、actions 和 getters,单独存放到一个 store 中会极大地增加代码的复杂性和维护难度,此时我们可以使用 module 在 Vuex 中进行模块化管理。在 using module 模式中,每个模块都拥有自己的 state、mutations、actions 和 getters,从而让代码更加清晰明了、易于维护。使用 module 的方法和常规的 Vuex store 相似,只是需要在 Vuex.Store() 中添加模块,如下所示:

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
})
Copy after login

如上代码所示,我们创建了一个名为 moduleA 的模块,然后在 store 中通过 modules 选项将其添加到了 Vuex 的 store 中。在组件中访问模块的 state、mutations、actions 和 getters,和访问常规的 Vuex store 中的一样,只需要在前面加上模块名即可,例如:

computed: {
  ...mapState('a', {
    count: state => state.count
  }),
  ...mapGetters('a', [
    'evenOrOdd'
  ])
},
methods: {
  ...mapMutations('a', [
    'increment'
  ]),
  ...mapActions('a', [
    'incrementAsync'
  ])
}
Copy after login

在组件中,使用 mapState、mapMutation、mapActions 和 mapGetters 进行访问和操作,可以更加方便和快捷地操作和维护模块的状态和数据。

六、总结

本文简要介绍了 Vue.js 的状态管理库 Vuex 的使用方法和常用场景,包括 state、mutation、action、getter 和 module 等几个核心概念的使用。Vuex 可以帮助我们有效地管理和共享应用程序中的各种状态值,提高代码的可维护性和可扩展性。在使用 Vuex 的过程中,我们还需要注意一些细节和坑点,如同步和异步操作、state 和 mutation 的使用规范等问题,需要认真掌握和注意。

The above is the detailed content of How to use Vuex for data management and state sharing?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template