提问人:JulienRobitaille 提问时间:11/10/2023 最后编辑:JulienRobitaille 更新时间:11/10/2023 访问量:40
在 vue 3 组合 api 中扩展和覆盖组件
Extend and override components in vue 3 composation api
问:
我有一个 vue 组件,它对许多其他人来说很常见。我希望能够在其他组件中继承此组件,在这些组件中,我可以覆盖一些函数或引用,同时重用模板和脚本部分中的大部分逻辑。我知道可组合函数。但它不能轻易适用于模板,不是吗?最好和最干净的方法是什么?
以下是通用组件的结构:
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>
我想在我想使用公共组件的特定组件中做类似的事情:
<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>
答:
1赞
MrSpt
11/10/2023
#1
这可以通过道具来实现。
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>
评论
0赞
JulienRobitaille
11/10/2023
确实你是对的!效果很好,也很干净,至少对于我没有通过道具进行大量覆盖的组件。谢谢!
0赞
MrSpt
11/10/2023
当你有大量的覆盖时,我会把它们打包在一个界面中,并将其作为道具传递。
评论