VueX中state中管理的数据(即状态),在组件中要访问时有4种写法;
定义一个简单的store.js文件,如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
count:0,
gender:'女',
age:20
},
mutations:{},
actions:{}
})
1、在组件中直接访问:
this.$store.state.数据名
//如访问gender
this.$store.state.gender
在组件的<template>中直接访问的时候,可以省略this:
<template>
<div>
<span>{{ $store.state.gender }}</span>
</div>
</template>
2、但是像1中那么写,要写很多$store.state ,很麻烦。可以在计算属性中声明,以减少书写$store.state.
在计算属性中声明有3种写法,第一种(computed中三种写法都是一样的):(我给count、gender都取了个新的名字——num、sex)
computed: {
num:function abcdefg(){
return this.$store.state.count
},
sex: function () {
return this.$store.state.gender
},
age(){
return this.$store.state.age
}
则,之后在组件中访问state的数据时,可以直接写:
<template>
<div>
<span>{{ num }}</span>
<span>{{ sex }}</span>
<span>{{ age }}</span>
</div>
</template>
3、但是第二种方法写的东西比第一种更多了...于是vuex给了一个函数mapState,来减少我们的工作量。
先在<script>中引入这个函数:
import { mapState } from 'vuex'
接着在computed中用,给mapState传入参数为一个对象,键表示我们定的别名,值为state中数据名,注意值要用引号括起来,否则将识别为该文件中函数。
computed: {
...mapState({
num:'count',
sex:'gender',
age:'age'
})
},
需要注意的是,调用mapState前加了三个点...
这个是js对象展开运算符。
为什么要加这三个点呢?
因为mapState函数返回值是一个对象,该对象里面包着三个函数(跟我们方法2写的函数一样的功能),大致就是:
{ num:f() , sex:f() , age:f() }
computed本来就是一个对象了,里面再包一个对象要报错,所以用三点展开。比如:
let obj1 ={ a:1,b:2}
let obj2 = { c:3, ...obj1}
console.log(obj2)
//{c: 3, a: 1, b: 2}
4、最后一种写法是项目里常见的写法,当我不给state中的数据取新名字,而用他原来的名字,即:
computed: {
...mapState({
count:'count',
gender:'gender',
age:'age'
})
},
可以简写为:(注意,给mapState函数传入参数为一个数组!)
computed: {
...mapState(['count','gender','age'])
},
同理,mapGetters、mapActions、mapMutations的用法一致。