vue3 状态管理 Vuex 4 / Pinia

41 阅读3分钟

vue3 状态、Vuex 4 / Pinia

Vuex 4

Vuex 4 是 Vue.js 官方推出的状态管理库,它提供了一种集中式管理应用程序中所有组件的状态的方式。Vuex 4 增强了 TypeScript 支持,还引入了一些新的概念,如模块化和插件化,使状态管理更加灵活和可维护。

Vuex 4 的核心概念包括:

  1. State:状态,即应用程序中需要共享的数据,类似于组件中的 data。
  2. Getters:用于从 state 中派生出其他状态的方法,类似于组件中的计算属性。
  3. Mutations:用于修改 state 中的数据的方法,但必须是同步的,类似于组件中的 methods。
  4. Actions:用于执行异步操作和提交 mutations 的方法,类似于组件中的 methods,但可以执行异步操作。
  5. Modules:用于将 store 分成多个模块,每个模块拥有自己的 state、getters、mutations 和 actions。 以下是一个简单的 Vuex 4 store 示例:
import { createStore } from 'vuex'

export default createStore({
  state: {
    count: 0
  },
  getters: {
    doubleCount(state) {
      return state.count \* 2
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    asyncIncrement(context) {
      setTimeout(() => {
      context.commit('increment')
      }, 1000)
    }
  },
  modules: {
  // ...
  }
})

在组件中,可以通过 useStore 函数来获取 store 的实例,然后通过 computed 或 methods 属性来访问状态或提交 mutations 和 actions:

import { useStore } from "vuex"

export default {
  setup() {
    const store = useStore()

    const increment = () => {
      store.commit("increment")
    }

    const asyncIncrement = () => {
      store.dispatch("asyncIncrement")
    }

    return {
      count: computed(() => store.state.count),
      doubleCount: computed(() => store.getters.doubleCount),
      increment,
      asyncIncrement,
    }
  },
}

需要注意的是,在 Vue 3 中,组件的 data、computed 和 methods 属性都已经被废弃,被 setup() 函数所代替。因此,在使用 Vuex 4 时,应该使用 setup() 函数中的 computed 和 methods 属性来访问状态和提交 mutations 和 actions。

除了 Vuex 4,Vue 3 还可以使用 Pinia 这个轻量级的状态管理库来管理应用的状态。要使用 Pinia,需要先安装并导入它 Pinia 速查表

import { createApp } from "vue"
import { createPinia } from "pinia"

const app = createApp({})

const pinia = createPinia()

app.use(pinia)

接下来,可以创建一个 Pinia Store:

import { defineStore } from "pinia"

export const useCounterStore = defineStore("counter", {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++
    },
  },
  getters: {
    doubleCount() {
      return this.count * 2
    },
  },
})

在上面的代码中,defineStore 函数定义了一个名为 counter 的 Store,state 函数中存储了应用的状态,actions 对象中存储了修改状态的方法,getters 对象中存储了对状态的计算属性。这些对象都可以通过 useCounterStore 函数进行访问。

在组件中,可以使用 useStore 函数来访问 store 对象:

import { useCounterStore } from "./store"

export default {
  setup() {
    const store = useCounterStore()

    const increment = () => {
      store.increment()
    }

    return {
      count: store.count,
      doubleCount: store.doubleCount,
      increment,
    }
  },
}

在上面的例子中,使用 useCounterStore 函数获取了 store 对象,然后可以通过 store 对象访问状态、修改状态等等。与 Vuex 4 不同的是,在 Pinia 中,可以使用类似于 Vue 2 中的 data、computed、methods 等属性来组织组件代码,而不需要使用 setup 函数。

需要注意的是,与 Vuex 4 不同的是,在 Pinia 中,状态的更新是同步的,不需要使用 commit 方法。此外,Pinia 还提供了许多钩子函数和选项,可以帮助开发者更方便地管理状态。