前言
Vuex 是一個專為 Vue.js 應用程序開發的狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
每一個 Vuex 應用的核心就是 store(倉庫)。“store”基本上就是一個容器,它包含着你的應用中大部分的狀態 (state)。Vuex 和單純的全局對象有以下兩點不同:
-
Vuex 的狀態存儲是響應式的。當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那么相應的組件也會相應地得到高效更新。
-
你不能直接改變 store 中的狀態。改變 store 中的狀態的唯一途徑就是顯式地提交 (commit) mutation。這樣使得我們可以方便地跟蹤每一個狀態的變化,從而讓我們能夠實現一些工具幫助我們更好地了解我們的應用。
store 的核心概念
State
state 表示了 store 中的狀態,類似於 vue 實例中的 data 屬性。
Mutation
更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation。
Vuex 中的 mutation 非常類似於事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是我們實際進行狀態更改的地方,並且它會接受 state 作為第一個參數
Action
Action 類似於 mutation,不同在於:
-
Action 提交的是 mutation,而不是直接變更狀態。
-
Action 可以包含任意異步操作。
一個示例
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
store 的用法
使用 store 之前, 先要安裝 vuex :
npm install vuex
安裝 Vuex 之后,讓我們來創建一個 store。創建過程直截了當——僅需要提供一個初始 state 對象和一些 mutation。
新建 store 文件夾,再新建 index.js 文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state){
state.count++;
}
}
})
為了在 Vue 組件中訪問 this.$store property,你需要為 Vue 實例提供創建好的 store。Vuex 提供了一個從根組件向所有子組件,以 store 選項的方式“注入”該 store 的機制。
也就是在 main.js 文件中導入,並注冊到 vue 根實例中:
import store from './store'
...
new Vue({
el: "#app",
store: store,
...
然后就可以在任意一個 vue 組件的 methods 方法屬性下通過 store.commit('increment')
來調用:
...
methods:{
increment:function(){
this.$store.commit("increment");
console.log(this.$store.state.count);
},
...
效果如下:
每次點擊,count 就會 +1.
參考資源
https://segmentfault.com/a/1190000023564695?utm_source=tag-newest
https://www.jianshu.com/p/eb23c72ab02a
每天學習一點點,每天進步一點點。