5

Imagine I have an application that has 10 components that are similar in some ways, but contain different content and some functional differences. But they all receive the same 3 props as a base (in other words they may define more but all define at least three specific props) they also all have 1 emit in common. They also also call const store = useStore() and have the same computed property that pulls a value from vuex store.

Is there a way I can create a composable or other strategy to let these components compose or inherit these common lines of code that are currently repeated in the src.

Example:

//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>

And another example:

//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>

Notice how there is a lot of repetition between these two, but there are key differences.

WillD
  • 5,170
  • 6
  • 27
  • 56
  • as defineProps and defineEmits are compiler macros, I don't think that there is a way to reuse them. the only thing that probably could be reused is the computed foo which you could extract into another composable. – Thomas Feb 04 '22 at 14:56
  • Could this help you? https://v3.vuejs.org/guide/component-provide-inject.html So you could inject your 3 props and use it by reference. But i am not sure how to use it in functional style. – Silvan Bregy Feb 04 '22 at 15:12

0 Answers0