vuex的核心使用

state:{
    
    
count:0
}
全局共享数据
this.$store.state.全局数据名称
例如 this.$store.state.count
**想访问谁就写全局数据(谁)**
mapState  映射
引入 当前需要的全局数据 ,映射
 当前的computed计算属性例如
import {
    
    mapState } from  'vuex'
全局数据  映射当前的计算属性
computed:{
    
    
...mapState(['count'])
}
mutations 用于变更 store的数据

**不可直接操作Store的数据**
mutations:{
    
    
aa(state){
    
    
//变更状态
state.count++
}
}
//触发mutation

mutations :{
    
    
add(state){
    
    
	state.count++
}
}
在组件中写个方法
methods:{
    
    
handel(){
    
    
this.$store.commit('add')
}
}
mutations{
    
    
 addN(state,step){
    
    
	//b变更
	state.count ++3
}
}
mutations :{
    
    
addN(state,step){
    
    
	state.count+=step
}
}
在组件中写个方法
methods:{
    
    
handel2(){
    
    
this.$store.commit('addN',3)
}
}

mutations :{
    
    
	add1(state){
    
    
	state.count--

}
addN(state,step){
    
    
	state.count-=step
}
}
组件
import {
    
    mapMutations } from  'vuex'
<button @click ="btn"></button>
methods:{
    
    
	...mapMutations(['add1']),
	btn(){
    
    
	this.add1()
}
	
}

猜你喜欢

转载自blog.csdn.net/qq_45424679/article/details/112855550