将Kendo UI Grid的OptionsAPI计算属性转CompositionAPI时遇报错求助
问题:Kendo Vue Grid本地化方法在Composition API中报错原因分析
背景代码
Options API 写法(正常运行)
gridSearchMessage() { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all columns..." ); }
Composition API 错误写法(触发报错)
const gridSearchMessage : ComputedRef<string> = computed<string>(() => { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all columns..." ) })
报错信息:Uncaught (in promise) Passed component - undefined is invalid. kendoui
Composition API 简化写法(正常运行)
const gridSearchMessage : ComputedRef<string> = computed<string>(() => { return "Search in all columns..." })
报错原因
在Composition API的setup函数(或<script setup>语法)中,this并不指向Vue组件实例,而是undefined。而provideLocalizationService方法必须接收一个有效的Vue组件实例作为参数,你传入的this是undefined,因此触发了"Passed component - undefined is invalid"的错误。
正确的Composition API写法
在Composition API中,需要通过getCurrentInstance获取当前组件实例的代理对象,再传入本地化方法:
import { computed, getCurrentInstance } from 'vue'; import { provideLocalizationService } from '@progress/kendo-vue-intl'; const instance = getCurrentInstance(); const gridSearchMessage: ComputedRef<string> = computed<string>(() => { if (!instance) return "Search in all columns..."; return provideLocalizationService(instance.proxy!).toLanguageString( "gridSearch", "Search in all columns..." ); });
说明:getCurrentInstance()返回的实例需通过.proxy获取组件代理对象,这个对象和Options API中的this功能等价,能被provideLocalizationService正确识别。
内容的提问来源于stack exchange,提问作者marinko
相关产品推荐
相关产品推荐

