关于Vuex的基本使用,一步一步清晰了解

基本使用流程

  1. 创建store
import vuex from "vuex"
export.default = new vuex.Store({
	state:{
		count:0
	}
})
  1. 绑定到根视图
vue.use(vuex)

new vue({
	store:store
})
  1. 视图使用
	this.$store.state.count
	//一般是在conputed的计算属性里获取

如何修改数据呢?

  1. 使用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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值