一: 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('确认') 会报错, 打印this为undefined
获取到的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('确认') // } }, }
后续遇到问题,继续更新