天天看點

vuex相關了解

重新整理資料不丢失

1.vue持久化 vue-presits插件

2.放在緩存中

vuex流程

引用vuex=>注冊vuex(Vue.use(vuex))=>new vuex=>導出放在vue執行個體上

vuex 相關屬性

1.state,mutation,action,modules,getter

2.mutation觸發commit action觸發是dispatch

modules中nameSpace用法以及傳參相關方法

nameSpace:true 調用dispatch()
const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,
      state: {...}, // 子產品内的狀态已經是嵌套的,namespaced不會有影響
      getters: {      // 每一條注釋為調用方法
        isAdmin () { ... } // getters['account/isAdmin']
      },
      actions: {
        login () {...} // dispatch('account/login')
     },
      mutations: {
        login () {...} // commit('account/login')
      },
      modules: {     // 繼承父子產品的命名空間
        myPage : {
          state: {...},
          getters: {
            profile () {...}     // getters['account/profile']
          }
        },
        posts: {    // 進一步嵌套命名空間
          namespaced: true,
          getters: {
            popular () {...}    // getters['account/posts/popular']
          }
        }
      }
    }
  }
})
           

如果你希望使用全局state和getter,roorState和rootGetter會作為第三和第四參數傳入getter,也會通過context對象的屬性傳入action

若需要在全局命名空間内分發action或者送出mutation,将{ root: true }作為第三參數傳給dispatch或commit即可。

modules: {
  foo: {
    namespaced: true,
    getters: {
      // 在這個被命名的子產品裡,getters被局部化了
      // 你可以使用getter的第四個參數來調用 'rootGetters'
      someGetter (state, getters, rootSate, rootGetters) {
        getters.someOtherGetter    // -> 局部的getter, ‘foo/someOtherGetter’
        rootGetters.someOtherGetter // -> 全局getter, 'someOtherGetter'
      }
    },
    actions: {
      // 在這個子產品裡,dispatch和commit也被局部化了
      // 他們可以接受root屬性以通路跟dispatch和commit
      smoeActino ({dispatch, commit, getters, rootGetters }) {
        getters.someGetter    // 'foo/someGetter'
        rootGetters.someGetter    // 'someGetter'
        dispatch('someOtherAction')      // 'foo/someOtherAction'
        dispatch('someOtherAction', null, {root: true})    // => ‘someOtherAction’
        commit('someMutation')    // 'foo/someMutation'
        commit('someMutation', null, { root: true })    // someMutation
      }
    }
  }
}
           

mutation,action的差別

1.mutation專注于修改state,而action專注于業務代碼,異步請求

2.mutation 必須同步執行,action可以異步

getter和state差別

就像計算屬性一樣,getter 的傳回值會根據它的依賴被緩存起來,且隻有當它的依賴值發生了改變才會被重新計算。

vuex為什麼不建議在action中修改state

當某種類型的action隻有一個聲明時,action的回調會被當作普通函數執行,而當如果有多個聲明時,它們是被視為Promise執行個體,并且用Promise.all執行(Promise.all在執行Promise時是不保證順序的)

繼續閱讀