关于在vue中使用i18n方法$t报错的问题

1,193 阅读1分钟

关于在vue中使用i18n方法$t报错的问题

  • 背景:在vue弹窗中,使用$t报错 vue.runtime.esm.js:1888 TypeError: Cannot read properties of undefined (reading '_t')
  • 猜测是this上$t方法的问题,由于项目急,我就没去探究为啥其他地方可以,el-dialog就报错了
  • 初步解决
import vm from "@/lang";
  data() {
    return {
      vm,
   };
  },
  // 方法中使用 vm.t("setting.pleaseFirstEnterPicName")
  // 模板中使用 :placeholder="vm.t('setting.selectClasify')"
  • 这时候初步解决了,但是新的问题来了,在全局的封装方法里,又遇到同样的问题。我的想法是,把这个t方法挂载到Vue上,于是乎在main.js中
import i18n from "@/lang";
Vue.prototype.$tLang = i18n.t;
  • 但是嘞,在组件中使用的时候,报错了vue-i18n.esm.js:1845 Uncaught (in promise) TypeError: this._getMessages is not a function
  • 这时候就有点懵了,我在组件中打印 vm.t === this.$tLang => true 那为啥全局的就不行
  • 根据报错信息_getMessages is not a function 我怀疑是this指向问题,一个是vm,一个是全局的this
  • 于是 在main.js中 Vue.prototype.$tLang = i18n.t.bind(i18n);
  • 解决