vue中使用 i18n 遇到的问题

2 篇文章 0 订阅

一: vue 报错解决:TypeError: Cannot read property ‘_t’ of undefined" 前端报错如下: [Vue warn]: Error in render: “TypeError: Cannot read property ‘_t’ of undefined”

是在项目中用了多语言配置,vue 跟 i18n之间的兼容问题。解决方法如下:

Vue.use(ViewUI, {
  i18n: (key, value) => i18n.t(key, value)
})

替换成

Vue.use(iView, {
  i18n: function(path, options) {
    let value = i18n.t(path, options)
    if (value !== null && value !== undefined) {
      return value
    }
    return ''
  }
})

国际化其他配置项不变


二: 使用i18n实现国际化功能,在切换语言状态时 ,js报错:

TypeError: Cannot read property ‘_t’ of null at VueComponent.Vue.$t (vue-i18n.esm.js?a925:178)
解决方案:

this.$t('')更改为 this.$root.$t('')


三: 获取组件的实例

在子组件的prop中,default的值想设置多语言, 直接使用this.$t('确认') 会报错, 打印thisundefined
在这里插入图片描述
获取到的VM实例,外部js仍然能自由调用VM的一切属性和方法。

<template>
</template>

<script>
// 1. 声明变量_this
let _this
export default {
    data() {
        return {},
        props: {
         title: {
	      type: String,
	      default: () => {
	      // 3. 使用 
	        return _this.$t('标题')
	      }
	    },
	    okText: {
	      type: String,
	      default: () => {
	        return _this.$t('确认')
	      }
	    },
	    cancelText: {
	      type: String,
	      default: () => {
	        return _this.$t('取消')
	      }
    },
		}
    },
    beforeCreate() {
        // 2.  在beforeCreate()中将当前组件的VM实例赋给变量_this
        _this= this
    }
}
</script>
****

对于上面这个问题,还有解决办法,特来更新

在data 里面, 声明变量接收 prop 里的值, 在渲染的时候, 直接使用声明的这个变量

data () {
    return {
      ok_Text: this.$t(this.okText)
    }
  },
  props: {
 title: {
      type: String,
      default: '标题'
      // default: () => {
      //   return _this.$t('标题')
      // }
    },
    okText: {
      type: String,
      default: '确认'
      // default: () => {
      //   return _this.$t('确认')
      // }
    },
}

后续遇到问题,继续更新

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值