Vue3组合式API中如何重写composable内的函数?
问题原因
你当前的写法无法生效的核心原因是:mainMethod 内部调用的是 useShareComp 函数作用域内的私有utilMethod变量,这个变量和组件内定义的同名函数属于完全独立的两个引用,外部无法直接修改composable内部的私有变量。
实现方案
方案1:通过参数传入自定义实现(推荐,类型安全)
修改composable,支持传入配置项,优先使用外部传入的自定义方法,没有传入就走默认实现,对原有逻辑侵入性最低。
修改后的useShareComp.ts代码:
// composable/useShareComp.ts import { ref } from 'vue' // 定义参数类型 interface UseShareCompOptions { utilMethod?: () => void } export function useShareComp(options?: UseShareCompOptions) { const toto = "hey"; const tata = ref(0); // 优先用传入的自定义方法,无传入则用默认实现 const utilMethod = options?.utilMethod ?? function() { 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 }; };
组件内使用时直接传入自定义的utilMethod即可:
// components/MyNewComp.vue script部分 import { useShareComp } from "@/composable/useShareComp"; const { toto, tata, mainMethod } = useShareComp({ utilMethod() { console.log("Util Method but in the MyNewComp!"); } });
方案2:基于实例属性重写(更接近类重写体验)
如果你需要和类继承一样的重写体验,可以修改composable内部逻辑,让mainMethod调用返回实例上的utilMethod,而非内部私有变量,外部可以直接替换实例上的方法实现重写。
修改后的useShareComp.ts代码:
// composable/useShareComp.ts import { ref } from 'vue' export function useShareComp() { const toto = "hey"; const tata = ref(0); // 先定义返回的实例对象 const instance = { utilMethod() { console.log("Util Méthod !!"); }, mainMethod() { console.log("Main Méthod !!"); console.log("should call the overriden or fallback to this utilMethod"); // 调用实例上的utilMethod,外部替换后会自动生效 instance.utilMethod() }, toto, tata } return instance };
组件内直接替换实例上的utilMethod即可:
// components/MyNewComp.vue script部分 import { useShareComp } from "@/composable/useShareComp"; const compInstance = useShareComp(); // 重写utilMethod compInstance.utilMethod = function() { console.log("Util Method but in the MyNewComp!"); } // 解构使用 const { toto, tata, mainMethod } = compInstance;
内容的提问来源于stack exchange,提问作者nicolidz
相关产品推荐
相关产品推荐

