【发布时间】:2021-11-05 01:33:55
【问题描述】:
假设我们有一个可比较的函数,如下所示:
// composable/useShareComp.ts
export function useShareComp() {
const toto = "hey";
const tata = ref(0);
function utilMethod() {
console.log("Util Méthod !!");
}
function mainMethod() {
console.log("Main Méthod !!");
console.log("should call the overriden or fallback to this utilMethod");
utilMethod()
}
return { toto, tata, utilMethod, mainMethod };
};
现在,我有 2 个组件将使用可组合方法。 (我用的是新的3.2版本)
// components/SharComp.vue
<template>
<h1>share comp</h1>
<p>{{toto}}</p>
<p>{{tata}}</p>
<button @click="mainMethod">call main method</button>
</template>
<script setup lang="ts">
import { useShareComp } from "@/composable/useShareComp";
const { toto, tata, mainMethod } = useShareComp();
</script>
所以上面如果调用mainMethod,它将简单地调用utilMethod,从而记录“Util Méthod !!”
但现在我想在另一个组件中覆盖utilMethod,如下面的代码所示
// components/MyNewComp.vue
<template>
<h1>MY NEW COMP</h1>
<p>{{toto}}</p>
<p>{{tata}}</p>
<button @click="mainMethod">call main method</button>
</template>
<script setup lang="ts">
import { useShareComp } from "@/composable/useShareComp";
const { toto, tata, mainMethod } = useShareComp();
function utilMethod() { // it will not override the utilMethod
console.log("Util Method but in the MyNewComp!");
}
</script
在 MyNewComp 组件中,我希望 utilMethod 被覆盖,因此当调用 mainMethod 时,它应该记录新的 console.log("Util Method but in the MyNewComp!");
从被覆盖的 utilMethod 中。
但我不知道如何做到这一点,因为我们可以轻松地使用一些原生类(和/或 vue-class-components 库)
【问题讨论】:
-
为什么不用 computed 代替 utilMethod 呢?
-
什么意思?可以举个例子吗?
标签: vue.js overriding vuejs3 vue-composition-api