图示
hooks>useState.js
import { useStore, mapState } from "vuex";
import { computed } from "vue";
export function useState(mapper) {
const store = useStore();
const storeStateFns = mapState(mapper);
const storeState = {};
Object.keys(storeStateFns).forEach((fnKey) => {
const fn = storeStateFns[fnKey].bind({ $store: store });
storeState[fnKey] = computed(fn);
});
return storeState;
}
Home.vue
<template>
<div class="home">
<table >
<h5>{{ name }}</h5>
<h5>{{ age }}</h5>
<h5>{{ counter }}</h5>
</table>
</div>
</template>
<script>
import { useState } from "../hooks/useState";
export default {
setup() {
const storeState = useState(["name", "age", "counter"]);
return {
...storeState,
};
},
};
</script>
<style></style>
感谢
非常感谢大神CoderWhy,可以看看他的课程