>[success] # state -- 扩展 ~~~ 1.上面的参数使用理解章节简单的示范了一下使用'state' 中的数据在组件中如何获 取值,是通过vue 实例上挂载'$store'对应的'state' 进行取值,关于为什么可以直接在vue实例获取 '$store'这部分可以参考'Vue -- 简单弄懂VueRouter过程'章节对'$router挂载vue实例的形式做参考' 还有一点考虑到计算属性的缓存特性才将'通过$store获取的state值放到了计算属性上' 2.官方文档中还给了更简单的使用方法,出发点往往'state'可能是大量的数据,每一次都需要 重复的去在计算属性定义其实往往这些操作代码都会去做统一跟方便的处理,同样官方 提供的'mapState 辅助函数',来减少这种'this.$store.state.存值的名称'重复性质的操作 ~~~ >[info] ## mapState 辅助函数 ~~~ 1.Vuex 给我们提供了辅助函数,使用的时候只需要引入辅助函数即可: import { mapState } from 'vuex' 2.上面的引入方式用了es6的结构赋值,相当于下面的写法: import vuex from 'vuex' const mapState = vuex.mapState ~~~ >[danger] ##### 官方给的几种写法 ~~~ 1.官方的第一种写法,就是我们案中的一种缩写形式 2.第二种是官方第一种的缩写形式 3.第三种为了方便获取this 进行组合形式的数据返回 ~~~ ~~~ export default { // ... computed: mapState({ // 箭头函数可使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了能够使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) } ~~~ ~~~ 4.第四种是一二种的缩写用,'使用数组'中直接包含'state' 中要使用的值 ~~~ ~~~ computed: mapState([ // 映射 this.count 为 store.state.count 'count' ]) ~~~ >[danger] ##### 项目中正确使用方式 ~~~ 1.首先计算属性不可能只有vuex 使用定义,可以通过解构的方式将这些vuex 通过辅助函数注入进去 ...mapState(['对应vuexstate中值名字']) ...mapState({'要在页面中使用的名称': 对应取Vuex中的state方法}) ~~~ * 用数组表达 ~~~ <template> <div> <p>{{appName}}</p> </div> </template> <script> import { mapState } from 'vuex' export default { name: "store", data(){ return{} }, methods:{}, computed:{ ...mapState([ 'appName', ]), // 在计算属性中 创建一个方法用来接受 vuex 中的stat // appName(){ // return this.$store.state.appName; // }, // userName(){ // return this.$store.state.user.userName; // } } } </script> <style scoped> </style> ~~~ * 对象的形式 ~~~ <template> <div> <p>{{appName}}</p> <p>{{userName}}</p> </div> </template> <script> import { mapState } from 'vuex' import state from "../store/state"; export default { name: "store", data(){ return{} }, methods:{}, computed:{ ...mapState({ appName:state => state.appName, userName: state => state.user.userName, // 使用module 中的state值 }), // 在计算属性中 创建一个方法用来接受 vuex 中的stat // appName(){ // return this.$store.state.appName; // }, // userName(){ // return this.$store.state.user.userName; // } } } </script> <style scoped> </style> ~~~