Vue JS + Vue Translate:如何在脚本标签内获取翻译字符串
在Vue组件中获取翻译字符串的正确方式
你直接在data的箭头函数里调用t('hello_world')行不通,核心原因是:data初始化阶段组件实例还未完全就绪,而且箭头函数的this不会指向组件实例,自然访问不到注入的翻译方法t。
下面给你几个可行的解决方案:
方案1:利用created钩子函数赋值
created是组件实例创建后立即执行的钩子,此时已经能访问到组件的t方法,我们可以在这里给text赋值:
<template> <div> {{ text }} </div> </template> <script> export default { data: () => ({ text: '' // 先初始化空值 }), created() { this.text = this.t('hello_world') } } </script>
方案2:使用计算属性(推荐)
如果你的翻译字符串需要随语言切换动态更新,计算属性是更优选择——它是响应式的,语言切换时会自动同步更新:
<template> <div> {{ text }} </div> </template> <script> export default { computed: { text() { return this.t('hello_world') } } } </script>
额外注意事项
如果你用的是vue-i18n,要确保项目已正确配置并注入到Vue实例中,比如在main.js里:
import Vue from 'vue' import VueI18n from 'vue-i18n' import messages from './translations' // 你的翻译文件 Vue.use(VueI18n) const i18n = new VueI18n({ locale: 'en', // 默认语言 messages }) new Vue({ i18n, render: h => h(App) }).$mount('#app')
只有正确配置后,组件实例上才会挂载t方法,你才能在钩子或计算属性中正常调用。
内容的提问来源于stack exchange,提问作者Leonardo Santos
相关产品推荐
相关产品推荐

