1. Create the Locales folder under Assets folder
locales–index.js –en.json –zh.json
2. The code in index.js is as follows
import Vue from 'vue' import VueI18n from 'vue-i18n' import enLocale from 'element-ui/lib/locale/lang/en' import zhLocale from 'element-ui/lib/locale/lang/zh-CN' import ElementLocale from 'element-ui/lib/locale' import store from '.. /.. /store/index' Vue.use(VueI18n) const DEFAULT_LANG = 'zh' const LOCALE_KEY = 'localeLanguage' const locales = { zh: { ... require('./zh.json'), ... zhLocale }, en: { ... require('./en.json'), ... enLocale }, } const i18n = new VueI18n({ locale: DEFAULT_LANG, messages: locales, silentTranslationWarn: true, }) ElementLocale.i18n((key, value) => i18n.t(key, value)) export const setup = lang => { if (lang === undefined) { lang = window.localStorage.getItem(LOCALE_KEY) } if (locales[lang] === undefined) { lang = DEFAULT_LANG } window.localStorage.setItem(LOCALE_KEY, lang) Vue.config.lang = lang i18n.locale = lang store.commit('CHANGE_LANG', lang) } var lang = navigator.language || navigator.userLanguage; lang = lang.substr(0, 2); if (lang ! = 'zh') { lang = 'en'; } const langArr = navigator.language.split('') const localeLang = window.localStorage.getItem(LOCALE_KEY) langArr.length = 2 setup(localeLang ? localeLang : langArr.join('') == 'en' ? langArr.join('') : null) export default i18nCopy the code
3, zh.json & en.json
{" sure ":" sure ", "cancel", "cancel"} {" sure ":" ok ", "cancel", "cancel"}Copy the code
4. Reference in main.js
import i18n from './assets/locales/index'
new Vue({
el: '#app',
router,
i18n,
store,
render: h => h(App)
})
Copy the code
5. Import setup method and add toggle button
import { setup } from "@/assets/locales/index"; < div class = "lang" > < span @ click = "change (' en ')" > ENG < / span > < span @ click = "change (' useful ')" > English < / span > < / div > change (flag) {if (flag == this.flag) { return false } setup(flag) }Copy the code
6. Use within components
// HTML this.$t(" confirm ") //jsCopy the code