一、安裝組件
npm install vue-i18n
二、在src/lang文件夾下新建cn.js和en.js
1、cn.js
export const m = {
hello: '你好'
}
2、en.js
export const m = {
hello: 'hello'
}
三、在src/i18n文件夾下新建index.js文件。沒有直接將這部分寫入main.js中是因爲在其他的js文件中可能會用到i18n,方便引入。
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh-CN',
messages: {
'zh-CN': require('@/lang/cn'),
'en-US': require('@/lang/en')
}
})
export default i18n
四、在main.js中引入i18n
import Vue from 'vue'
import App from './App'
import router from './router'
import i18n from './i18n'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
render: h => h(App),
router,
i18n,
components: { App },
template: '<App/>'
})
五、在 .vue文件中使用示例
1、在標籤中使用,例
<div>{{ $t('m.hello')}}<div>
2、在js代碼中使用,例
let h = this.$t('m.hello')
3、當this.$i18n.locale='zh-CN'時,1和2中的值是 '你好';當this.$i18n.locale='en-US'時,1和2中的值是 'hello'。
六、在其他js文件中引入i18n,直接import
import i18n from '@/i18n'