vux管理state要映射到某个组件内的变量,应在computed中而不是在data里面(data是有缓存的,Vuex中值改变了,没法做到响应,在computed中,虽然也有缓存,但会自动监视依赖)。
在组件里面
export default{
//错误写法
data(){
return {
number: this.$store.state.number
}
},
//正确写法
computed:{
number(){
return this.$store.state.number
}
}
}
上述写法其实可以简洁些(如果有十个数据要映射就要写十个这样的方法,太麻烦),vue 提供了 mapState 函数,它把state 直接映射到我们的组件中。
使用mapState 之前要先引入它。两种用法(接受一个对象,或接受一个数组)
对象的方法
import {mapState} from "vuex"; // 引入mapState
export default {
// 下面这两种写法都可以
computed: mapState({
count: state => state.count // 组件内的每一个属性函数都会获得一个默认参数state, 然后通过state 直接获取它的属性更简洁
count: 'count' // 'count' 直接映射到state 对象中的count, 它相当于 this.$store.state.count,
})
}
数组的方法
import {mapState} from "vuex";
export default {
computed: mapState(["count"])// 数组
}
mutations映射,两种用法(接受一个对象,或接受一个数组)
import { mapMutations } from 'vuex'
export default {
methods: {
//数组形式
...mapMutations([
'increment' // 映射 this.increment() 为 this.$store.commit('increment')
]),
//对象形式
...mapMutations({
add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
})
}}