在單獨的js文件裏用i18n

在.vue文件裏,能夠經過this.$t直接使用掛在Vue原型上的Vue.prototype.$t
若是須要在抽出來的js文件裏使用,能夠這麼寫:vue

// 文件i18n/zh.js
let zh = {
    title: '這是標題'
}

export default zh
// 文件i18n/en.js
let en = {
    title: 'This is a title'
}

export default en
// 文件i18n/index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import utils from './../utils/utils'

import en from './en'
import zh from './zh'

Vue.use(VueI18n)  //會把$t掛到Vue.prototype上,以便在.vue文件中使用this.$t()

// 國際化
const i18n = new VueI18n({
    locale: utils.getCookie('language') || 'zh',// set locale
    messages: {
        zh: zh, // 中文語言包
        en: en // 英文語言包
    }
})

export default i18n

而後能夠經過i18n.t()使用:this

// 文件test.js

import i18n from './i18n/index'

let title = i18n.t('title')
console.log(title)

我使用的vue版本爲2.6.7,vue-i18n版本8.9.0。
有問題能夠評論留言prototype

相關文章
相關標籤/搜索