Vuex基础-Getter
官方地址:https://vuex.vuejs.org/zh/guide/getters.html
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 会暴露为 store.getters 对象,可以以属性的形式访问这些值,也可以以方法访问这些值。
目录结构:

index.js:
import Vue from 'vue' import Vuex from 'vuex' import state from "./state" import getters from './getters' import mutations from "./mutations" import actions from "./actions" import user from './module/user' Vue.use(Vuex) export default new Vuex.Store({ state, getters, mutations, actions, modules: { user } })
getters.js:
//通过方法访问getters //你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。 const getters = { appNameWithVersion: (state) => { return `${state.appName}v2.0` } } export default getters
user.js:
const state = { // userName:'Caoqi' } const getters = { firstLetter: (state) => { return state.userName.substr(0, 1) } } const mutations = { // } const actions = { // } export default { namespaced:true,//有利于模块更加密闭,不受外界的干扰 state, getters, mutations, actions }
store.vue:
<template>
<div>
<a-input :value="inputValue" @input="handlerInput"></a-input>
<p>{{ inputValue }} -> lastLetter is {{ inputValueLastLetter }}</p>
<p>appName: {{ appName }}, appNameWithVersion : {{ appNameWithVersion }}</p>
<p>userName : {{ userName }}, firstLetter is : {{ firstLetter }}</p>
</div>
</template>
<script>
import AInput from "_c/AInput.vue";
import AShow from "_c/AShow.vue";
//变量的解构赋值
import { mapState, mapGetters } from "vuex";
import { stat } from "fs";
export default {
name: "store",
data() {
return {
inputValue: ""
};
},
components: {
AInput: AInput,
AShow: AShow
},
computed: {
//ES6展开操作符 mapState展开会形成一个对象 使用对象展开运算符将此对象混入到外部对象中
...mapState({
appName: state => state.appName
}),
...mapState("user", {
userName: state => state.userName
}),
// 使用对象展开运算符将 getter 混入 computed 对象中
// ...mapGetters(["appNameWithVersion"]),
appNameWithVersion() {
//通过属性访问getters,Getter 会暴露为 store.getters 对象,可以以属性的形式访问这些值:
return this.$store.getters.appNameWithVersion;
},
...mapGetters("user", ["firstLetter"]),
inputValueLastLetter() {
return this.inputValue.substr(-1, 1);
}
},
methods: {
handlerInput(val) {
this.inputValue = val;
}
}
};
</script>
浙公网安备 33010602011771号