这里以中英文切换为例:
1. 安装 nuxt-i18n npm install nuxt-i18n -S
2.新建lang 文件夹,放置语言包
zh.js
const zh = {
index: '首页',
list:'列表'
}
export default zh
en.js
const en = {
index: 'Home',
list:'list'
}
export default en
3.新建i18n.js 配置文件
import zh from './lang/zh'
import en from './lang/en'
// 加载element-ui语言包
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
const mergeZH = Object.assign(zhLocale.default, zh);
const mergeEN = Object.assign(enLocale.default, en);
const I18N = {
locales: [{
code: 'en',
iso: 'en-US',
name: 'English'
},
{
code: 'zh',
iso: 'zh-ZH',
name: '中文'
}
],
defaultLocale: 'zh',
vueI18n: {
fallbackLocale: 'zh',
messages: {
en: mergeEN,
zh: mergeZH
}
}
}
export default I18N
4.添加中间件:lang.js,切换语言时,更改路由,同时更新store中语言类型
import getCookie from '@/config/get-cookie'
export default function ({store, route, redirect, req}) {
const {lang} = getCookie(req)
if (lang) {
store.commit('setLang', lang)
}
const routePath = route.path
if (store.state.lang === 'en' && routePath.indexOf(`/${store.state.lang}/`) === -1) {
console.log('redirect')
return redirect({path: `/${store.state.lang}${routePath}`, query: route.query})
}
}
4. store中添加mutaion:
setLang(state, lang) {
state.lang = lang
}
5.在nuxt.config.js中配置module
import I18N from './config/i18n'
module.exports = {
modules: [
['nuxt-i18n', I18N],
]
}
6. plugins/element-ui.js
import Vue from 'vue'
import Element from 'element-ui/lib/element-ui.common'
export default ({
app
}) => {
Vue.use(Element, {
i18n: (key, value) => app.i18n.t(key, value)
})
}
7.切换语言组件
<template>
<span class="lang-switcher">
<nuxt-link v-for="(locale, i) in showLocales" :key="i" :to="switchLocalePath(locale.code)">
<span @click="handleChangeLang(locale.code)">点击切换{{ locale.name }}</span>
</nuxt-link>
</span>
</template>
<script>
const Cookie = process.client ? require("js-cookie") : undefined;
export default {
name: "LangSwitcher",
computed: {
showLocales() {
return this.$i18n.locales.filter(
locale => locale.code !== this.$i18n.locale
);
}
},
methods: {
handleChangeLang(lang) {
this.$store.commit("setLang", lang);
Cookie.set("lang", lang);
}
}
};
</script>
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。