使用vue-i18n 报Cannot read property '_t' of undefined

1,066 阅读1分钟

转自 segmentfault.com/q/101000001… 在vue extend的插件中取不到i18n挂在vue prototype的方法,我是直接import i18n的实例,然后写个方法去i18n的messages里面取

import i18n from '@/i18n/'

/**
 * 插件里面使用i18n
 * @param path 引用的路径
 * @returns String 对应译文
 */
export function $i18n(path) {
    let locale = i18n.locale;
    let messages = i18n.messages;
    let lang = messages[locale];
    let getText = (path) => {
        const array = path.split('.');
        let current = lang;
        let value = ''
        for (let i = 0, j = array.length; i < j; i++) {
            current = current[array[i]]
            if(!current){
              break;  
            }
            if(i === j - 1){
                value = current;
            }
        }
        return value || path;
    }
    return getText(path)
}