Vuex 學習筆記
VUEX是什麼?
用來解決元件之間共用資料問題的一個外掛
-
Vuex 內部結構
- State 就是被共用的資料(但是不可以被直接操作,不可以直接訪問)
- Mutations 可以直接操作(Mutate) State 中的資料,可以定義 State 中的資料如何被改變
- Actions 可以觸發 Mutations 對States的改變,該觸發操作專業名詞為commit
-
Components 與Vuex的互動
- 通過 dispatch Actions 的方式來改變 State
- 通過Render來讀取State中的資料
Vuex的使用方法
- 新建一個store.js檔案(位置可以自選)
-
在該檔案中引入vue和vuex,並在vue中啟用vuex
Improve vue from 'vue' Improve vuex from 'vuex' vue.use(vuex)
-
在該檔案中配置 state,mutations,actions
//這裡的state是資料實際儲存的地方 const state={ count:10 } const mutations={ add(state,param){ state.count += param }, reduce(state,param){ state.count -= param } } const actions={ add:({commit},param)=>{ commit('add',param) }, reduce:({commit},param)=>{ commit("reduces",param) } }
-
只有一個store配置的方法
-
將以上配置在Vuex物件中例項化並匯出
export default new vuex.Store({ state, mutations, actions })
-
在main.js中引用該vuex的store例項
improt store from './store' new vue ({ ...... store, ...... })
-
在元件中使用vuex的store例項
在頁面中引用該例項state的值$store.state.count
引入該例項的actions
import {mapActions} from ‘vuex’ export default { methods:mapActions([‘add’,’reduce’]) }
頁面使用actions
@click='add(param)'
@click='reduce(param)'
-
-
有多個store配置的方法
-
將以上配置在Vuex物件中例項化並匯出
export default new vuex.Store({ module:{ a: { state, mutations, actions } } })
-
在main.js中引用該vuex的store例項
improt store from './store' new vue ({ ...... store, ...... })
-
在元件中使用vuex的store例項
在頁面中引用該例項state的值$store.state.a.count
呼叫該例項的actions
import {mapActions} from ‘vuex’ export default { methods:mapActions('a',[‘add’,’reduce’]) }
頁面使用actions
@click='add(param)'
@click='reduce(param)'
-
這篇筆記主要是本人學習Vuex時候的知識總結,如果有不對的地方還請多多斧正