首页 > 代码库 > vuex笔记

vuex笔记

https://vuex.vuejs.org/
首先先创建一个xxx.js文件
代码如下
import Vue from ‘vue‘;
import Vuex from ‘vuex‘;
Vue.use(Vuex);
const state={
count:1
};
//需要去处理的逻辑方法
const mutations={
add(s){
s.count+=5;
},
reduce(state){
state.count-=5;
}
}
//export default可以让外部引用
export default new Vuex.Store({
state,
mutations
})

在xxx.vue中调用这个js文件
import store from ‘@/vuex/store‘
store,
在xxx.vue中如何调用 add()方法,如下
规定写法
<button @click=" $store.commit(‘add‘)" >加</button>
调用对象的属性
<h3>{{ $store.state.count }}</h3>
state访问状态对象
1:{{count1}}
computed: {
count1(){
return this.$store.state.count
}
},
2:
import{ mapState} from ‘vuex‘
computed: mapState({
count1:s=>s.count
}),
3:数组
{{count}}
computed: mapState([‘count‘]),

Mutations修改状态
加参数
const mutations={
add(s,num){
s.count+=num;
},
reduce(state,s1){
state.count-=s1;
}
}
<button @click=" $store.commit(‘add‘,5)" >加</button>
<button @click=" $store.commit(‘reduce‘,5)" >减</button>
简化操作
import{ mapState,mapMutations} from ‘vuex‘
<button @click=" add(5)" >加</button>
<button @click=" reduce(5)" >减</button>
methods:mapMutations([
‘add‘,‘reduce‘
]),
getters计算过滤操作
const getters ={
count(s){
return s.count+=50
}
};
export default new Vuex.Store({
state,
mutations,
getters
})
computed: {
...mapState([‘count‘]),
count(){
return this.$store.getters.count
}
},
或者
import{ mapState,mapMutations,mapGetters} from ‘vuex‘
computed: {
...mapState([‘count‘]),
...mapGetters([‘count‘])
},

actions异步修改状态
actions是异步的改变state状态,而Mutations是同步改变状态
const actions={
addActive(context){
context.commit(‘add‘,3)
},
reduceActive({commint}){
commint(‘reduct‘)
}
};
export default new Vuex.Store({
state,
mutations,
getters,
actions
})
import{ mapState,mapMutations,mapGetters,mapActions} from ‘vuex‘
methods:{
...mapMutations([
‘add‘,‘reduce‘
]),
...mapActions([‘addActive‘,‘reduceActive‘])
},
增加异步请求
addActive(context){
context.commit(‘add‘,3);
setTimeout(()=>{
context.commit(‘reduce‘,4)
},4000);
console.log(‘比reduct提前执行了‘)
},

vuex笔记