How to use I18N for internationalization in VUE
One, foreword
The project needs to achieve multi-language switch, at this time to contact internationalization, there are numerous front-end frameworks, several popular frameworks have internationalization plug-in tools to match. Such as:
vue + vue-i18n
angular + angular-translate
react + react-intl
jquery + jquery.i18n.property
Ii. Internationalization of Vue project
Here to vUE using VUE-I18N this plug-in internationalization function
1. Install vuE-I18N dependencies in your own project first.
npm install vue-i18n --S
Copy the code
Create i18n instance object and add it to main.js:
| - main. | js import documents -- -- i18n | -- index. Js object instance is created | - | languages various language pack - en - us. Js English package | useful - cn. Js Chinese packageCopy the code
i18n/index.js
Create i18N instance object as follows:
Import Vue from 'Vue' import VueI18n from 'vue-i18n' vue. use(VueI18n) const i18n = new VueI18n({import Vue from 'Vue' import VueI18n from 'vue-i18n' vue. use(VueI18n) locale: 'zh', messages: { 'zh': require('./languages/zh_cn'), 'en': require('./languages/en_us') } }) export default i18nCopy the code
- Next we need to create two new JS files (or josn files) as the language package.
The code in the zh.js Chinese package isi18n/languages/zh
:
Module. exports = {message: {login: 'welcome ', lang:{zh:' Chinese ', en: 'English'}}}Copy the code
- Mount i18N instance object to Vue instance:
main.js
import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import "@/assets/plugins/element-ui"; import i18n from '@/assets/plugins/i18n'; Router, store, render: (h) => h(App),}).$mount("# App ");Copy the code
- Chinese and English switch button, the code is as follows:
<template> <div> <div class="lang"> <el-radio-group v-model="language" size="mini"> <el-radio label="zh" border>{{ $t("message.lang.zh") }}</el-radio> <el-radio label="en" border>{{ $t("message.lang.en") }}</el-radio> </el-radio-group> </div> </div> </template> <script> import Vue from "vue"; export default { data() { return { language: "zh", }; Function (val) {val === "zh"? (this.$i18n.locale = "zh") : (this.$i18n.locale = "en"); ,}}}; </script>Copy the code
# Add vUE – I18n data rendering template syntax
/ / the vue component templates to use < div > {{$t (' message. Useful ')}} < / div > / / vue component template data binding using the < input: placeholder = "$t (' message. Useful ')" > < / input > Data :{MSG :this.$t('message.zh'); }Copy the code