在static/lang下新建文件:
index.js、en.js、zh.js...
// en.jsmodule.exports = { route: { title: 'chengdu', } }// zh.jsmodule.exports = { route: { title: '成都', } }// index.jsimport path from 'path'import fs from 'fs'let files = fs.readdirSync(path.join('./', 'static', 'lang'))let langPack = {}for (let file of files) { if (file !== 'index.js') { langPack[file.replace(/.js/, '')] = require(`./${file}`) }}export deafult langPack
然后在src/store/plugins下的i18n.js中使用插件方式引入vue-i18n
import * as types from '../types'import VueI18n from 'vue-i18n'import langPack from '@/../static/lang'import Vue from 'vue'Vue.use(VueI18n)export const i18n = new VueI18n({ locale: 'zh', messages: langPack,})function i18nPlugin (store) { store.subscribe((mutation, state) => { if (mutation.type === types.SET_LANGUAGE) { i18n.locale = mutation.payload.toString() } })}export default i18nPlugin
记得要在store/index.js中引入插件以及使用mutation的方式改变state。