基本使用流程
- 创建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的计算属性里获取
如何修改数据呢?
- 使用commit来调用mutation
export.default = new vuex.Store({
state:{
count:0
},
mutations:{
ins(state){
state.count++
}
}
})
//视图层调用
this.$store.commit('ins')
获取变化后的state里面的数据,
使用store里面的computed
getters:{
money : ()=>`${state.count}*1000`
}
this.$store.getters.money
异步化更改数据
上面的motation是同步的,下面使用Action来异步化
actions:{
insAsy( {commit} ){
setTimeout(()=>{
commit('ins'). //commit是默认参数,解析于store
},1000)
}
}
//视图
this.$store.dispatch('insAsy')
dispatch传递参数给store
this.$store.dispatch('insAsy',{
data:10
})
actions:{
insAsy( store,args ){
setTimeout(()=>{
store.commit('ins',args)
},1000)
}
}
ins(state,args){
//dosomething
}
简化代码
如果视图需要更多的state数据,那么我们可以这样
import { mapState } from 'vuex'
//计算属性里面取出需要的
computed: {
...mapState({
sidebar: state => state.app.sidebar,
device: state => state.app.device,
}),
}
也可以简化Action
method:{
...mapActions([ins])
...mapMutations(['insAsy'])
}
//直接调用
this.ins()
网友评论