1. 程式人生 > 其它 >vuex基礎用法

vuex基礎用法

state 存放全域性資料
this.$store.state.***
this.$store.commit('addFn',引數)
this.$store.dispath('addAsync',引數)
修改 state資料需要呼叫
state:{
**:''
}
mutation中不能處理一步操作
mutation:{
addFn(state,(引數)){
state.** -= 引數
}
}
元件呼叫
import {mapState,mapMutations,mapActions } form 'vuex'
// 計算屬性存放state 值
computed:{
...mapState(['state內值'])
}
methods:{
...mapMutations([
'mutation中定義的函式(addFn)
])
...mapMutations({
add: 'addFn' // 將 `this.add()` 對映為 `this.$store.commit('increment')`
})
}
元件函呼叫mutation 傳入函式
fatherClick(){
store.commit('addFn')
// store.commit('add')
}

當處理值發生非同步則需要呼叫 action

actions:{
// 在actions中,不能直接修改 state 中資料
// 必須通過 context.commit() 觸發某個 mutation才行
addAsync(context){
傳送的請求
setTimeout(()=>{
context.commit('addFn')
},1000)
}
}
元件呼叫函式
fatherClick(){
// dispatch 函式,專門觸發 action
第一中呼叫方法
this.$store.dispatch('addAsync')
}
第二種呼叫方法
methods:{
...mapActions(['addAsync'])
}
fatherClick(){
this.addAsync()
// 可以直接寫在按鈕事件上 @click=“addAsync”
}