图解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c3a2d4f79ec36233e0355a4b94e56908.png)
hooks>useMapper.js
import { useStore } from "vuex";
import { computed } from "vue";
export function useMapper(mapper, mapFunc) {
const store = useStore();
const gettersFns = mapFunc(mapper);
const getters = {};
Object.keys(gettersFns).forEach((key) => {
const fn = gettersFns[key].bind({ $store: store });
getters[key] = computed(fn);
});
return getters;
}
hooks>useState.js
import { mapState } from "vuex";
import { useMapper } from "./useMapper";
export function useState(mapper) {
return useMapper(mapper, mapState);
}
hooks>useGetters.js
import { useMapper } from "./useMapper";
import { mapGetters } from "vuex";
export function useGetters(mapper) {
return useMapper(mapper, mapGetters);
}
hooks>index.js
import { useGetters } from "./useGetters";
import { useState } from "./useState";
export { useGetters, useState };
引用useGetters的文件:Home.vue
<template>
<div class="home">
<table border="1">
<h2>{{ $store.getters.totalBooksPrice }}</h2>
<h2>{{ $store.getters.info }}</h2>
<hr />
<h2>{{ totalBooksPrice }}</h2>
<h2>{{ info }}</h2>
</table>
</div>
</template>
<script>
// import { useGetters } from "../hooks/useGetters";
import { useGetters } from "../hooks/index";
export default {
setup() {
return {
...useGetters(["totalBooksPrice", "info"]),
};
},
};
</script>
<style></style>