如何在Nuxt插件同一文件的主函数内调用另一个函数
如何在Nuxt插件的同一文件中在mainFunc内部调用anotherFunc?
你的需求是在Nuxt插件的provide对象中,让mainFunc调用同一对象内的anotherFunc,原代码直接调用会因为作用域或变量未定义问题报错,以下是两种可行的解决方案:
原问题代码
export default defineNuxtPlugin((nuxtApp) => { return { provide: { // my main function mainFunc: () => { return `hello ${anotherFunc()}`; }, // i want to use this inside the main anotherFunc: () => { return 'Another Func'; }, } }; });
解决方案1:提前定义函数再挂载到provide
先在插件函数内部定义两个函数,再将它们挂载到provide对象中,这样两个函数可以直接互相引用,不受定义顺序影响:
export default defineNuxtPlugin((nuxtApp) => { // 提前定义函数 const anotherFunc = () => { return 'Another Func'; }; const mainFunc = () => { return `hello ${anotherFunc()}`; }; return { provide: { mainFunc, anotherFunc } }; });
解决方案2:使用普通函数通过this调用
将箭头函数改为普通函数,此时this会指向provide对象,就能通过this.anotherFunc()调用同一对象内的方法(无需调整函数顺序):
export default defineNuxtPlugin((nuxtApp) => { return { provide: { mainFunc: function() { return `hello ${this.anotherFunc()}`; }, anotherFunc: function() { return 'Another Func'; } } }; });
原代码报错原因
- 直接调用
anotherFunc()时,该变量在mainFunc的作用域内尚未定义(anotherFunc在mainFunc之后声明); - 使用箭头函数时,
this不会指向provide对象,无法通过this.anotherFunc访问目标方法。
内容的提问来源于stack exchange,提问作者Abdelrhman Qouay
相关产品推荐
相关产品推荐

