天天看点

setup使用mapState hooks封装 批量引入Vuex中的数据图示hooks>useState.jsHome.vue感谢

图示

setup使用mapState hooks封装 批量引入Vuex中的数据图示hooks>useState.jsHome.vue感谢

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,可以看看他的课程

继续阅读