这里仅展示vue-cli中使用vuex的基本流程跟顺序,这里不讲vuex如何引入项目中
一、首先是最基本的定义一个全局变量state
const state = {
count: 1,
}
我们在使用的时候需要取出这个全局变量,有两种方式
第一种,直接在template中使用
<template>
<div>
$store.state.count
</div>
</template>
第二种,导入mapState然后在计算属性中使用
import { mapState } from 'vuex'
<template>
<div>
{{count}}
</div>
</template>
computed: {
...mapState({'count'}),
},
二、假设我们需要修改state中的值,此时我们就需要使用mutations
定义一个mutations方法对state中的值进行修改
const mutations = {
ADD_COUNT: (state, view) => {
state.count += view
}
}
第一种修改方式,直接在方法中调用commit修改state的值
this.$store.commit('ADD_COUNT', 3)
第二种修改方式,引入mapMutation
import { mapMutations } from 'vuex'
//然后在methods中对使用这个方法
methods: {
...mapMutations({
add: 'ADD_COUNT' // 将 `this.add()` 映射为 `this.$store.commit('ADD_COUNT')`
})
//调用
this.add(3)
}
三、但是假设你需要使用个定时器,异步地修改state的值,你会发现mutations无法修改到state中的值,这个时候你就需要使用到action
定义一个action
const actions = {
asyncAddCount({ commit },num) {
setTimeout(()=>{
//注意这里调用的是mutations中的提交方法
commit('ADD_COUNT',num)
},1000)
},
}
第一种使用方式
//methods中直接修改,跟commit差不多
this.$store.dispatch('asyncAddCount',3)
第二种,使用mapAction,跟mapMutations差不多
...mapActions({
add: 'asyncAddCount' // 将 `this.add()` 映射为 `this.$store.dispatch('asyncAddCount')`
})
this.add(3)
四、假设你需要取出state时做一些判断或者过滤,比如state是1,你取出来想要乘2,就可以使用getter
定义一个getter
getters: {
getCount: (state) => {
return state.count * 5
}
}
取的话就跟state的取差不多
第一种
this.$store.getters.getCount
第二种
<template>
<div>{{getCount}}</div>
</template>
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'getCount'
])
}
}