Vue组件i18n $t未定义报错及动态导航翻译问题
问题分析
你遇到的$t is not defined错误,核心原因是**$t是vue-i18n挂载在组件实例上的翻译方法,直接在组件顶级作用域的数组中调用时,组件实例还未初始化,无法访问到$t**。另外你尝试的{{ $t("fullservice") }}是Vue模板语法,只能用在<template>标签内,不能写在JavaScript代码里。
解决方案
根据你使用的Vue版本(Composition API/Options API),提供两种可行写法:
1. Vue 3 Composition API(<script setup>)
通过useI18n钩子获取翻译函数t,再用它定义导航数组。如果需要语言切换时自动更新翻译内容,建议把数组做成计算属性:
<script setup> import { useI18n } from 'vue-i18n' import { computed } from 'vue' // 获取翻译函数 const { t } = useI18n() // 用computed包裹,实现语言切换时自动更新 const navigation = computed(() => [ { name: "Full Service", route: "/fullService", }, { name: t("verkauf"), route: "/sale", }, { name: t("vermietung"), route: "/rental", }, { name: "Streaming", route: "/streaming", }, { name: "Smart Home", route: "/smartHome", }, { name: t("kontakt"), route: "/contact", }, { name: t("impressum"), route: "/imprint", }, { name: t("cookieRichtline"), route: "/cookiePolicy", } ]) </script> <template> <div v-for="item in navigation" class=" text-mst_white text-bold transform transition duration-300 hover:text-mst_orange py-5 px-2 "> <router-link :to="item.route">{{ item.name }}</router-link> </div> </template>
2. Vue 3 Options API / Vue 2
将导航数组定义在computed计算属性中,此时可以通过this.$t访问翻译方法:
<script> export default { computed: { navigation() { return [ { name: "Full Service", route: "/fullService", }, { name: this.$t("verkauf"), route: "/sale", }, { name: this.$t("vermietung"), route: "/rental", }, { name: "Streaming", route: "/streaming", }, { name: "Smart Home", route: "/smartHome", }, { name: this.$t("kontakt"), route: "/contact", }, { name: this.$t("impressum"), route: "/imprint", }, { name: this.$t("cookieRichtline"), route: "/cookiePolicy", } ] } } } </script> <template> <div v-for="item in navigation" class=" text-mst_white text-bold transform transition duration-300 hover:text-mst_orange py-5 px-2 "> <router-link :to="item.route">{{ item.name }}</router-link> </div> </template>
内容的提问来源于stack exchange,提问作者Miguel Portero
相关产品推荐
相关产品推荐

