Vue 3 中 props、emits、useStore 的代码重用

Wil*_*llD 5 javascript typescript vuejs3 vue-composition-api composable

想象一下,我有一个应用程序,它有 10 个组件,这些组件在某些方面相似,但包含不同的内容和一些功能差异。但它们都接收相同的 3 个 props 作为基础(换句话说,它们可能定义更多,但都定义至少 3 个特定的 props),它们也都有 1 个共同的发射。它们还调用const store = useStore()并具有相同的计算属性,从 vuex 存储中提取值。

有没有一种方法可以创建可组合的或其他策略,让这些组件组合或继承当前在 src 中重复的这些通用代码行。

例子:

//component 1
<script lang="ts" setup>

import { useStore } from 'vuex';

const store = useStore();

const props = defineProps<{
  a: number;
  b: string;
  c: boolean;
  uniqueToComp1: string;
}>();

const foo = computed(() => store.state.bar[props.a]);
const uniqueConstForComp1 = computed(() => props.a + Math.random());

const emit = defineEmits<{
  (e: 'exit'): void;
}>();

</script>
Run Code Online (Sandbox Code Playgroud)

另一个例子:

//component 2
<script lang="ts" setup>

import { useStore } from 'vuex';

const store = useStore();

const props = defineProps<{
  a: number;
  b: string;
  c: boolean;
  uniqueToComp2: Function;
}>();

const foo = computed(() => store.state.bar[props.a]);
const uniqueConstForComp2 = computed(() => props.a - 8);

const emit = defineEmits<{
  (e: 'exit'): void;
}>();

</script>
Run Code Online (Sandbox Code Playgroud)

请注意这两者之间有很多重复,但也有关键的区别。