I have a vue component that is common for many others. I wish to be able to inherit this component in other components where I can override some functions or ref, while reusing the template and most of the logic in the script section. I am aware of the composable functions. But it cant easily be applicable for templates, isnt it? What would be the best and cleanest way to do so?
Here is what the structure of the common component looks like:
common.vue:
<template>
<div>
<div>Title</div>
<div>{{refToOverride.value}}</div>
</div>
</template>
<script>
import { defineComponent, ref} from 'vue';
export default defineComponent({
name: "common"
setup() {
const refToOverride= ref("object to override");
function functionToOverride() {
return "Override me!"
}
return {
refToOverride,
functionToOverride,
};
},
});
</script>
And I would like to do something like that, in the a specific component in which I want to use the common component:
<template>
<div>
<common/>
</div>
</template>
<script>
import { defineComponent} from 'vue';
import { common } from ./common.vue
export default defineComponent({
components: {common}
setup() {
common.refToOverride.value = ref("I override a ref");
common.functionToOverride() = function() {
return "I override a function!"
})
},
});
</script>
This can be achieved just with props.
BaseComponent.vue
<script setup lang="ts">
interface Props {
text: string
myFunction: () => string
}
defineProps<Props>()
</script>
<template>
<div>{{ text }}</div>
<div>{{ myFunction() }}</div>
</template>
SpecialComponent.vue
<script setup lang="ts">
const specialFunction = () => {
return 'I am special'
}
const specialText = ref<string>('I am so special')
</script>
<template>
<base-component :my-function="specialFunction" :text="specialText" />
</template>