In the project, you need to customize the Chinese / English switch. Based on vue.js, combined with vue-i18n and ElementUI, the following are the usage methods.
ElementUI internationalization link: http://element-cn.eleme.io/#/...
vue-i18n: https://github.com/kazupon/vu...
Installation: npm install vue-i18n
vue.js+vue-i18n internationalization
To use vue.js+vue-i18n without using ElementUI first:
Create a new I18N folder at the same level of main.js, in which the i18n.js and langs folders are created, and under the langs folder, the en.js and cn.js are created. The directory is as follows:
//i18n.js import Vue from 'vue' import VueI18n from 'vue-i18n' import messages from './langs' Vue.use(VueI18n) //Get the user's language selection from localStorage. If not, the default is Chinese. const i18n = new VueI18n({ locale: localStorage.lang || 'cn', messages, }) export default i18n
//langs/index.js import en from './en'; import cn from './cn'; export default { en: en, cn: cn }
//en.js const en = { message: { 'hello': 'hello, world', } } export default en;
//cn.js const cn = { message: { 'hello': 'Hello, the world', } } export default cn;
//main.js add the following code import i18n from './i18n/i18n'; window.app = new Vue({ el: '#app', router, store, i18n, template: '<App/>', components: { App } })
The next step is to use and switch languages in the page.
//html: <p>{{$t('message.hello')}}</p> // hello, world
//js switch language data() { return { lang: 'en' } }, methods: { switchLang() { this.$i18n.locale = this.lang } }
By changing the value of this.$i18n.locale, you can automatically switch the page language, en,ja,cn... Etc
vue.js+vue-i18n+elementUI internationalization
There are not many changes, as follows
//i18n.js import Vue from 'vue' import locale from 'element-ui/lib/locale'; import VueI18n from 'vue-i18n' import messages from './langs' Vue.use(VueI18n) //Get the user's language selection from localStorage. If not, the default is Chinese. const i18n = new VueI18n({ locale: localStorage.lang || 'cn', messages, }) locale.i18n((key, value) => i18n.t(key, value)) //In order to realize multilingual switching of element plug-in export default i18n
//en.js import enLocale from 'element-ui/lib/locale/lang/en' const en = { message: { 'hello': 'hello, world', }, ...enLocale } export default en;
//cn.js import zhLocale from 'element-ui/lib/locale/lang/zh-CN' const cn = { message: { 'hello': 'Hello, the world', }, ...zhLocale } export default cn;