Appearance
getters
某些属性我们可能需要经过变化后来使用,这个时候可以使用 getters:
javascript
const store = createStore({
state() {
return {
rootCounter: 100
}
},
getters: {
doubleRootCounter(state) {
return state.rootCounter * 2
}
},
mutations: {
increment(state) {
state.rootCounter++
}
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vue
<div>
<h2>{{$store.getters.totalPrice}}</h2>
</div>
1
2
3
2
3
getters 第二个参数
javascript
getters: {
totalPrice(state, getters) {
let totalPrice = 0;
for(const book of state. books) {
totalPrice += book.count * book.price;
}
return totalPrice + ',' + getters.myName;
}
},
myName (state) {
return state.name;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
getters 的返回函数
getters 中的函数本身,可以返回一个函数,那么在使用的地方相当于可以调用这个函数
javascript
getters: {
totalPrice(state, getters) {
let totalPrice = 0;
for(const book of state. books) {
totalPrice += book.count * book.price;
}
return totalPrice;
}
},
myName (state) {
return state.name;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
mapGetters 的辅助函数
javascript
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(["nameInfo", "ageInfo", "heightInfo"]),
...mapGetters({
sNameInfo: "nameInfo",
sAgeInfo: "ageInfo"
})
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
vue3
javascript
import { mapGetters, createNamespacedHelpers } from 'vuex'
import { useMapper } from './useMapper'
export function useGetters(moduleName, mapper) {
let mapperFn = mapGetters
if (typeof moduleName === 'string' && moduleName.length > 0) {
mapperFn = createNamespacedHelpers(moduleName).mapGetters
} else {
mapper = moduleName
}
return useMapper(mapper, mapperFn)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
javascript
import { useGetters } from '../hooks/useGetters'
export default {
computed: {
},
setup() {
const storeGetters = useGetters(["nameInfo", "ageInfo", "heightInfo"])
return {
...storeGetters
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13