Vue3中使用i18n,this.$t报错

本文介绍了在Vue项目中实现国际化(i18n)的三种方法:方案一是通过全局挂载$t;方案二是使用vue-i18n并设置`legacy`为`false`;方案三是利用选项式写法直接在组件中使用`this.$t`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方案一 

//需要把$t手动挂载到全局 

//main.js
app.config.globalProperties.$t = i18n.global.t
//需要使用的时候在组件里引用
import { getCurrentInstance  } from 'vue'
const _this = getCurrentInstance().appContext.config.globalProperties
console.log('$i18n',_this.$t('欢迎'))

方案二

legacy设置为false

//main.js
const i18n = createI18n({
  locale: localStorage.getItem('i18n-lang'),
  fallbackLocale: 'zh',
  messages: {
    en,
    zh
  },
  legacy: false
})
//组件中先引用再使用
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
console.log('$i18n',t("欢迎"))

方案三

直接像vue2一样,使用选项式写法,可以直接使用

//使用vue选项式写法,可以直接使用this.$t
<script>
export default {
  methods:{
    change(){
      console.log(this.$t('欢迎'))
    }
  },
  mounted() {
    this.change()
  }
}
</script>

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值