入门Vuex

State

获取State中的值的三种方法

  1. 直接在模板里面写
1
<p>{{ $store.state.count }}</p>
  1. 通过计算属性
1
2
3
4
5
computed: {
count(){
return this.$store.state.count
}
}
  1. 通过mapstate
1
computed: mapState(['count'])

Mutations

  1. 直接写在模板里面(不传值)
1
<button @click="$store.commit('add')">+</button>
  1. 通过mapmutations(推荐,传值不传值都可以使用)
1
2
3
4
5
6
7
8
const mutations = {
add(state){
state.count++;
},
reduce(state,n){
state.count-=n;
}
}
1
2
3
methods: {
...mapMutations(['reduce','add'])
}
1
2
<button @click="add()">+</button>
<button @click="reduce(5)">-</button>

getters

  1. 一般写法
1
2
3
const getters = {
count : state => state.count+=100
}
1
2
3
4
5
6
computed: {
...mapState(['count']),
count(){
return this.$store.getters.count
}
}
  1. 简写
1
2
3
const getters = {
count : state => state.count+=100
}
1
2
3
4
computed: {
...mapState(['count']),
...mapGetters(['count'])
}

actions

1
2
3
methods: {
...mapActions(['addAction','reduceAction'])
}
1
2
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>
1
2
3
4
5
6
7
8
9
10
11
12
const actions = {
addAction({commit}){
commit('add');
setTimeout(()=>{commit('reduce',3)},2000);
console.log('我比reduce提前执行');
},
reduceAction(context){
context.commit('reduce',5);
setTimeout(()=>{context.commit('add')},2000);
console.log('我比reduce提前执行');
}
}