Vuex 學習筆記

VUEX是什麼?

用來解決組件之間共用數據問題的一個插件
  • Vuex 內部結構

    • State 就是被共用的數據(但是不可以被直接操作,不可以直接訪問)
    • Mutations 可以直接操作(Mutate) State 中的數據,可以定義 State 中的數據如何被改變
    • Actions 可以觸發 Mutations 對States的改變,該觸發操作專業名詞爲commit
  • Components 與Vuex的交互

    • 通過 dispatch Actions 的方式來改變 State
    • 通過Render來讀取State中的數據

Vuex的使用方法

  1. 新建一個store.js文件(位置可以自選)
  2. 在該文件中引入vue和vuex,並在vue中啓用vuex

    Improve vue from 'vue'
    Improve vuex from 'vuex'
    vue.use(vuex)
  3. 在該文件中配置 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配置的方法

    1. 將以上配置在Vuex對象中實例化並導出

      export default new vuex.Store({
          state,
          mutations,
          actions
      })
    2. 在main.js中引用該vuex的store實例

      improt store from './store'
      new vue ({
          ......
          store,
          ......
      })
    3. 在組件中使用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配置的方法

    1. 將以上配置在Vuex對象中實例化並導出

      export default new vuex.Store({
          module:{
             a: {
                  state,
                  mutations,
                  actions
              }
          }
      })
    2. 在main.js中引用該vuex的store實例

      improt store from './store'
      new vue ({
          ......
          store,
          ......
      })
    3. 在組件中使用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時候的知識總結,如果有不對的地方還請多多斧正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章