小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前文我们学习 Vuex
将请求到的数据通过定义路由, 展示到页面中, 由于在模板页面中获取数据书写方法比较繁琐, 本文就学到了Vuex 为我们提供的方便, 四个辅助功能函数. 我们也可以学习其中的思想, 在工作中多写一些功能函数: xxx-helper.js
前言:
Vuex 官方文档: vuex.vuejs.org/zh/
Vuex 四个辅助函数
前文学习的使用 mutations
和 actions
的方法, 在页面使用时通过调用对应的方法, 这样的写法, 如果数据比较少, 我们写一条两条三条还可以, 但是如果要获取的数据比较多就不太方便了 e!
为此 Vuex 给我们提供了四个辅助函数, 方便在模板中调用 Vuex 中的数据及方法:
四个辅助函数
mapState
mapGetters
mapMutations
mapActions
下面在代码中演示如何使用这几个辅助方法函数
在下面演示中, 将前文用到的方法注释掉, 通过对比理解其用法:
<template>
<div id="app">
<!-- <img src="./assets/logo.png"> -->
<!-- {{n}}:{{$store.getters.isGood}} -->
{{ num.n }}:{{ isGood }}
<!-- <button @click='inc(3)'>加</button> -->
<button @click="changeN(3)">加</button>
<!-- <button @click='inc(-5)'>减</button> -->
<button @click="changeN(-5)">减</button>
<!-- <button @click='asyncinc(8)'>异步加</button> -->
<button @click="asyncChangeN(8)">异步加</button>
<router-view />
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
name: 'App',
computed: {
// n() {
// return this.$store.state.num.n
// },
...mapState(['num', 'n']), /// num 模块名 n 变量名
...mapGetters(['isGood']),
},
created() {
// this.$store.dispatch('getList',"users");
// this.$store.dispatch('getList',"goods");
this.getList('users')
this.getList('goods')
},
methods: {
// inc(p){
// this.$store.commit("changeN",p);
// },
// asyncinc(p){
// this.$store.dispatch("asyncChangeN",p)
// }
...mapActions(['getList', 'asyncChangeN']), /// 异步
...mapMutations(['changeN']), /// 同步
},
}
</script>
参考 官方文档
- Vuex 官方文档: vuex.vuejs.org/zh/
- Vuex 官方文档-辅助函数: vuex.vuejs.org/zh/