在 Vuex 中,有一些常用的屬性可以幫助你管理應用程序的狀態。這些屬性包括 state、getters、mutations 和 actions。
-
state
: 用于存儲應用程序的狀態數據,是 Vuex 存儲數據的地方。當應用程序中的多個組件需要共享狀態時,就可以將這些共享的狀態存儲在 state 中。const store = new Vuex.Store({state: {count: 0} })
-
getters
: 用于從 store 中的 state 中派生出一些狀態,類似于計算屬性。可以對 state 中的數據進行過濾、排序或任何其他操作后返回結果。const store = new Vuex.Store({state: {todos: [{ id: 1, text: 'Learn Vue', done: true },{ id: 2, text: 'Build an app', done: false }]},getters: {doneTodos: state => {return state.todos.filter(todo => todo.done)}} })
-
mutations
: 用于修改 store 中的 state,在 Vuex 中,state 的唯一方法是提交 mutation,只能同步執行。const store = new Vuex.Store({state: {count: 1},mutations: {increment (state) {state.count++}} })
-
actions
: 類似于 mutations,不同之處在于提交的是 mutation,而不是直接變更狀態。可以包含任意異步操作。const store = new Vuex.Store({state: {count: 1},mutations: {increment (state) {state.count++}},actions: {incrementAsync ({ commit }) {setTimeout(() => {commit('increment')}, 1000)}} })
這些屬性結合使用可以幫助你更好地管理應用程序的狀態。通常情況下,當你需要統一的狀態管理,并且組件之間需要共享狀態時,使用 Vuex 是一個很好的選擇。例如,當你開發一個大型單頁應用(SPA)時,會更傾向于使用 Vuex 來管理應用的復雜狀態。
在實際開發中,通常會同時使用 state、getters、mutations 和 actions 這些屬性,以便更好地組織和管理應用的狀態。通過 state 存儲數據,getters 派生狀態,mutations 修改狀態,actions 處理異步操作,可以使應用的狀態管理更加清晰和易于維護。