在单独的js文件里用i18n

6次阅读

共计 643 个字符,预计需要花费 2 分钟才能阅读完成。

在.vue 文件里,可以通过 this.$t 直接使用挂在 Vue 原型上的 Vue.prototype.$t
如果需要在抽出来的 js 文件里使用,可以这么写:

// 文件 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() 使用:

// 文件 test.js

import i18n from './i18n/index'

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

我使用的 vue 版本为 2.6.7,vue-i18n 版本 8.9.0。
有问题可以评论留言

正文完
 0