基本使用流程
- 創(chuàng)建store
import vuex from "vuex"
export.default = new vuex.Store({
state:{
count:0
}
})
- 綁定到根視圖
vue.use(vuex)
new vue({
store:store
})
- 視圖使用
this.$store.state.count
//一般是在conputed的計(jì)算屬性里獲取
如何修改數(shù)據(jù)呢?
- 使用commit來調(diào)用mutation
export.default = new vuex.Store({
state:{
count:0
},
mutations:{
ins(state){
state.count++
}
}
})
//視圖層調(diào)用
this.$store.commit('ins')
獲取變化后的state里面的數(shù)據(jù),
使用store里面的computed
getters:{
money : ()=>`${state.count}*1000`
}
this.$store.getters.money
異步化更改數(shù)據(jù)
上面的motation是同步的,下面使用Action來異步化
actions:{
insAsy( {commit} ){
setTimeout(()=>{
commit('ins'). //commit是默認(rèn)參數(shù),解析于store
},1000)
}
}
//視圖
this.$store.dispatch('insAsy')
dispatch傳遞參數(shù)給store
this.$store.dispatch('insAsy',{
data:10
})
actions:{
insAsy( store,args ){
setTimeout(()=>{
store.commit('ins',args)
},1000)
}
}
ins(state,args){
//dosomething
}
簡化代碼
如果視圖需要更多的state數(shù)據(jù),那么我們可以這樣
import { mapState } from 'vuex'
//計(jì)算屬性里面取出需要的
computed: {
...mapState({
sidebar: state => state.app.sidebar,
device: state => state.app.device,
}),
}
也可以簡化Action
method:{
...mapActions([ins])
...mapMutations(['insAsy'])
}
//直接調(diào)用
this.ins()