vue狀態管理vue-vux使用


一.state --- 數據

簡單使用
1.Vue.use(Vuex)
2.注入,new vue({
el:...
store,
...
})
3.然后在所有組件中可以通過$store.state.xxx獲取,動態數據,通過computed可以實時更新

二.getters --- 獲取數據 (局部或默認狀態,其他getter,根狀態)

對state中的數據過濾或者計算
getters:{
    todoDone:state=>{
        return state.todos.filter(todo=>todo.done)
    },
    將todos遍歷,每條為todo傳入匿名函數,返回todo.done為真的那條
    todoDoneLength:(state,gettrers){
        renturn getters.todoDone.length
    }
    接受getters作為第二參數,使用getters后的數據
}

三.Mutations --- 數據更新 (局部或默認狀態,載荷)

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state,payload) {
      // 變更狀態 不能使用異步函數的回調
      state.count=state.count+payload.data
    }
  }
})

然后
store.commit("increment",{
    data:10
})
或者
store.commit({
type:"increment",
payload:{}
})

觸發事件,更改數據,payload載荷,設置為對象更易讀

四.actions --- 可以異步執行mutations

(類store,通過參數解構{state,rootState,commit},內部直接使用,不用帶context)
(一般在組件中就只調用actions)

在actions內放置異步函數,然后觸發mutation內的事件
actions:{
    increment (context){
        context.commit("increment")
    }或者
    increment ({commit}){
        commit("increment")
    }
}
context是一個與store實例相同的對象
{commit}是通過參數結構將context中的commit方法當做參數傳入

通過store.dispatch("increment")

*通過promise等組合actions,即一個actions調用完后調用下一個actions事件

五. modules --- 模塊化狀態樹

類似於vue的模塊使用方法

const module_a={
    state:{},
    mutations:{}...
}

var store = new Vuex.Store({
    modules:{
        a:module_a,
        b:module_b
    }
})

然后通過store.state.a.count 訪問數據
mutation 和 getter :  第一個參數是模塊的局部狀態
action : context.state 是局部狀態,根節點的狀態是 context.rootState
getter : 根狀態會作為第三個參數

命名空間---因為mutations等都是全局的,所以通過將變量名設為來設置命名空間
如:

const TDONE = "TODO/DONE"
然后 type form xxx.js
[type.TDONE] (state) {
...
}

其他

一.表單處理

v-model綁定如果是引用類,就會在修改value時,直接修改state
解決:

通過set,get方法
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM