Vuex 是一个用于 Vue.js 应用程序的状态管理模式。它集中管理应用程序中的所有组件的状态,并提供了一种可预测的方式来修改和响应状态的变化。

在 Vue3 中,Vuex 的使用方式与 Vue2 中基本相同,但有一些细微的变化。

  1. 创建 store 实例 在 Vue3 中,创建 Vuex 的 store 实例的方式与 Vue2 中相同,使用 createStore 方法来创建一个 store 实例。
import { createStore } from 'vuex'

const store = createStore({
  // state, mutations, actions, getters
})
  1. 定义 state 在 Vue3 中,定义 state 的方式与 Vue2 中相同,通过在 store 实例中定义一个 state 对象来管理应用程序的状态。
const store = createStore({
  state() {
    return {
      count: 0
    }
  }
})
  1. 定义 mutations 在 Vue3 中,定义 mutations 的方式与 Vue2 中相同,通过在 store 实例中定义一个 mutations 对象来修改 state 的值。
const store = createStore({
  state() {
    return {
      count: 0
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})
  1. 定义 actions 在 Vue3 中,定义 actions 的方式与 Vue2 中相同,通过在 store 实例中定义一个 actions 对象来处理异步操作和提交 mutations。
const store = createStore({
  state() {
    return {
      count: 0
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  }
})
  1. 定义 getters 在 Vue3 中,定义 getters 的方式与 Vue2 中相同,通过在 store 实例中定义一个 getters 对象来获取 state 的值。
const store = createStore({
  state() {
    return {
      count: 0
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  },
  getters: {
    doubledCount(state) {
      return state.count * 2
    }
  }
})

这些是 Vue3 中使用 Vuex 的基本内容。通过使用 Vuex,我们可以更好地管理和响应应用程序中的状态变化,并在组件之间共享状态。


原文地址: https://www.cveoy.top/t/topic/o3fQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录