vuex 允許在 vue.js 2 中管理全局響應(yīng)式狀態(tài),具體步驟如下:安裝 vuex;創(chuàng)建存儲(chǔ),包含狀態(tài)、獲取器、變異函數(shù)和動(dòng)作;將存儲(chǔ)集成到應(yīng)用程序;在狀態(tài)對(duì)象中聲明全局狀態(tài);使用 mapstate 獲取狀態(tài);使用 commit 調(diào)用變異函數(shù)修改狀態(tài);使用動(dòng)作執(zhí)行異步操作并分派變異函數(shù)。
如何使用 Vuex 在 Vue.js 2 中管理狀態(tài)
Vuex 是 Vue.js 的一個(gè)狀態(tài)管理庫,它允許您在 Vue 應(yīng)用程序中管理全局響應(yīng)式狀態(tài)。以下是如何在 Vue.js 2 中使用 Vuex:
1. 安裝 Vuex
使用 npm 或 Yarn 安裝 Vuex:
npm install vuex
登錄后復(fù)制
或
yarn add vuex
登錄后復(fù)制
2. 創(chuàng)建 Store
在 Vuex 中,狀態(tài)存儲(chǔ)在一個(gè)稱為 Store 的對(duì)象中。創(chuàng)建一個(gè)新的 Store:
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
// 初始狀態(tài)
},
getters: {
// 計(jì)算屬性
},
mutations: {
// 變異函數(shù)
},
actions: {
// 異步操作
}
})
export default store
登錄后復(fù)制
3. 集成 Store
將 Store 集成到您的 Vue 應(yīng)用程序中:
import store from './store'
new Vue({
store,
// ...
})
登錄后復(fù)制
4. 狀態(tài)
在 state 對(duì)象中聲明您的全局狀態(tài):
state: {
count: 0
}
登錄后復(fù)制
5. 取值
使用 Vuex 中的 mapState 輔助函數(shù)來獲取狀態(tài):
computed: {
...mapState(['count'])
}
登錄后復(fù)制
6. 變異函數(shù)
變異函數(shù)是用于修改狀態(tài)的唯一方法。使用 commit 方法來調(diào)用變異函數(shù):
methods: {
increment() {
this.$store.commit('increment')
}
}
登錄后復(fù)制
7. 動(dòng)作
動(dòng)作是用于執(zhí)行異步操作的函數(shù)。它們可以分派變異函數(shù)或觸發(fā)其他動(dòng)作:
actions: {
async fetchItems() {
// 異步操作
this.$store.commit('setItems', items)
}
}
登錄后復(fù)制
通過遵循這些步驟,您可以在 Vue.js 2 中使用 Vuex 來管理全局響應(yīng)式狀態(tài),從而實(shí)現(xiàn)更復(fù)雜和可維護(hù)的應(yīng)用程序。






