国际化 Vue-i18n的安装与使用 (Vue2.0 / Vue3.0)
一、Vue-i18n是什么?
Vue-I18n是 Vue.js 的国际化插件。它可以轻松地将一些本地化功能集成到你的 Vue.js 应用程序中。简单来说就是可以帮助用户进行语言的切换”
二、使用步骤
1.引入库
代码如下(示例):
//npm
npm install vue-i18n --save-dev//yarn
yarn add vue-i18n
2.在locales文件夹创建 en.json / zh.json
//en.json
{"up":"up","chooseVariants":"Choose Variants","Specifications":"Product Specifications"
}//zh.json
{"up":"起","chooseVariants":"请选择产品规格","Specifications":"产品规格",
}
3.在locales文件夹创建 index.js
import {createI18n} from 'vue-i18n';import en from './en.json'
import zh from './zh.json'//const locale = 'zh'
let locale = 'zh'
const messages = {'en': en,'zh': zh
}
if(localStorage.getItem('lang')){locale = localStorage.getItem('lang')
}const i18n = createI18n({locale: locale,messages
})export default i18n;
4.创建 store.js
import i18n from '../locales'export default createStore({state: {locales: [{code: 'en',name: 'English'},{code: 'zh',name: '中文'},],locale: '',},mutations: {SETLANG(state,lang){state.locale= langlocalStorage.setItem('lang', lang);i18n.global.locale = lang}},actions: {},modules: {},getters: {}
})
5.使用方法
{{ $t(“chooseVariants”) }}
6.语言切换示例
<template><div class="language" @click.stop><div class="language-div hor-center slgap" @click="langed = !langed"><img class="world" src="@/assets/common/world.svg" alt="" /><div class="body1" :class="{ 'body-langed': langed }">{{ $t("languages") }}</div><imgsrc="@/assets/common/chevronDown.svg"class="language-img":class="{ 'img-rotate': langed }"/></div><div class="language-box col" :class="{ 'language-hidden': !langed }"><divclass="language-label flex"v-for="(lang, i) in locales":key="i"@click="switchLang(lang.code)">{{ lang.name }}</div></div></div>
</template>//Vue2.0
<script>
export default {head() {return {htmlAttrs: {lang: this.$store.state.locale,},};},name: "SwitchLang",data() {return {langed: false,};},methods: {switchLanguage(localeCode) {document.cookie = `locale=${localeCode}`;location.reload();},},computed: {locales() {return this.$store.state.locales;},locale() {return this.$store.state.locale;},},created() {// PubSubs.PubSub.subscribe("closeComps", () => {// this.langed = false;// });},
};
</script>//Vue3.0
<script setup>
import { useStore } from "vuex";
const store = useStore();
function switchLang(lang) {location.reload();store.commit("SETLANG", lang);
}
</script>
<style scoped>
</style>