Vue3 <script setup>+TS中使用Vue-i18n报$t未定义的解决方法
编辑补充
我之前在<script setup>中无法调用$t(key: string)的原因,是没有按规范将翻译方法声明为局部变量,多谢评论区开发者指出问题。
解决方法很简单,只需要添加一行解构代码即可:
const { t } = useI18n();
之后直接调用t方法就能正常运行,示例:
var message = computed(() => t(TranslationKeys.Message))
希望遇到同样问题的开发者能少走弯路,我之前卡了很久都没定位到问题。以下是原始提问内容。
原始问题
我在Vue3项目中搭配TypeScript、Vue-I18n使用<script setup>语法时遇到了报错。之前我在Vue3的composition风格下用过I18n,没出什么问题,旧写法如下:
<script lang="ts"> import { TranslationKey } from "@/i18n/translationkeys"; import { Vue } from "vue-class-component"; export default class Navbar extends Vue{ data() { return { workAgreement: this.$t(TranslationKey.WorkAgreement), documentation: this.$t(TranslationKey.Documentation) } } } </script>
但切换到<script setup>后,在script标签里直接用$t()会抛出如下错误:
Cannot find the name '$t'(找不到名称'$t')
但这个方法在<template/>标签里是可以正常使用的。
之前我都是在script标签里通过data()函数声明、获取翻译变量,现在Vue调整了data/setup的相关逻辑,我不清楚新语法下要怎么正确实现。
复现场景
我的HelloWorld.vue组件中,模板部分代码运行正常:
<template> <h2>{{ $t(TranslationKeys.Message) }}</h2> <v-btn @click="changeLanguage">Change language</v-btn> </template>
但<script setup>部分的代码调用$t()时就会报“找不到名称'$t'”的编译错误,代码如下:
<script setup lang='ts'> import { LanguageType } from '@/resources/languageTypes'; import { TranslationKeys } from '@/resources/translationKeys'; import { useRootStore } from '@/store/root/rootStore'; import { computed } from 'vue'; var message = computed(() => {$t(TranslationKeys.Message)}) var store = useRootStore(); function changeLanguage() { store.SetLanguage(store.GetCurrentLanguage == LanguageType.DK ? LanguageType.EN : LanguageType.DK); } </script>
如果是我遗漏了文档中的相关内容,在此提前致歉。
内容的提问来源于stack exchange,提问作者SleepDeprivedMango
相关产品推荐
相关产品推荐

