vue 国际化在弹出框中$t()报错:TypeError: Cannot read property '_t' of undefined

vue 国际化在弹出框中$t()报错

在做项目的时候基本会用到弹出框,如果你像我这样自己写了一个弹出框就可能会出现国际化的错误

const setDialog = function (component, opts) {
    const DialogComponent = Vue.extend(component);
    opts = opts || {};
    var dialogComponent = new DialogComponent({
        store,
        el: document.createElement('div'),
        propsData: opts
    });
    opts.component = dialogComponent;
    dialogComponent.$dialog = Vue.$koallDialog(opts);
    dialogComponent.$on('okCallback', opts.okCallback || function () {});
    dialogComponent.$on('errCallback', opts.errCallback || function () {});
    dialogComponent.$on('removeDialog', dialogComponent.$dialog.removeDialog);
    return dialogComponent;
};
util.setDialog = setDialog;

因为国际化是后面的需求加的,所以前面的坑可能就没考虑这一块,然后在弹出框里面写国际化就报错了

<FormItem :label="$t('operation.zw') " prop="title">
    <Input v-model="formLeft.title" name="title">Input>
FormItem>

报错内容:

vue.esm.js:571 [Vue warn]: Error in render: "TypeError: Cannot read property '_t' of undefined"
(found in )
vue.esm.js:1687 TypeError: Cannot read property '_t' of undefined
    at Proxy.Vue.$t (vue-i18n.esm.js:103)
    at Proxy.render (addI18n.vue?bbdf:39)
    at VueComponent.Vue._render (vue.esm.js:4390)
    at VueComponent.updateComponent (vue.esm.js:2690)
    at Watcher.get (vue.esm.js:3033)
    at new Watcher (vue.esm.js:3022)
    at mountComponent (vue.esm.js:2694)
    at VueComponent.Vue$3.$mount (vue.esm.js:8226)
    at VueComponent.Vue$3.$mount (vue.esm.js:10540)
    at VueComponent.Vue._init (vue.esm.js:4486)

解决办法

  1. 在main.js文件中把vue挂载到window。window.vm = new Vue({ el: '#app', i18n: i18n,...})
  2. 在弹出的窗口中获取window.vm
	data () {
            const vm = window.vm;
            return {
                vm: vm,
                ...
                }
         	}
  1. 在html中加上vm,加在$t前面
<FormItem :label="vm.$t('operation.zw') " prop="title">
    <Input v-model="formLeft.title" name="title">Input>
FormItem>
<p>{{vm.$t('login.error')}}p>

大功告成!!

你可能感兴趣的:(前端)