使用Nuxt.js和Vue-i18n重定向到同一页面但切换语言URL
公司最近提出一个需求,就是当用户切换语言的时候,在路由中需要将其选中的语言加入到路由中
例如网址:
localhost/about
应该通过该方法(通过按特定按钮)重定向到:
localhost/bg/about
Nuxt文档中所建议的,用于使用Vue-i18n进行本地化https://nuxtjs.org/examples/i18n/
在 Nuxt 官网中也给出了国际化的例子,但是并不满足公司的这个需求,大家有兴趣可以去看下
在 components
文件夹下面新建 LangSelect.vue
文件
<template>
<el-dropdown trigger="click" class="international" @command="handleSetLanguage">
<div>
<i class="el-icon-share">{{$t('home.changelang')}}</i>
</div>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item :disabled="language==='zh'" command="zh">中文</el-dropdown-item>
<el-dropdown-item :disabled="language==='en'" command="en">English</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</template>
<script>
export default {
computed: {
language() {
return this.$store.state.locale;
}
},
methods: {
handleSetLanguage(language) {
this.$i18n.locale = language;
console.log(this.$i18n.locale);
this.$store.commit("SET_LANG", language);
// console.log(this.$store.state.locale, "locale");
var beforePath = this.$nuxt.$router.history.current.path;
// -- Removing the previous locale from the url
var changePath = this.$store.state.locale
var result = "";
result = beforePath.replace("/en", "");
result = result.replace("/zh", "");
this.$nuxt.$router.replace({ path: "/" + changePath + result });
this.$message({
message: "Switch Language Success",
type: "success"
});
}
}
};
</script>
在middleware
文件中新建i18n.js
export default function ({ isHMR, app, store, route, params, error, redirect }) {
const defaultLocale = app.i18n.fallbackLocale
// If middleware is called from hot module replacement, ignore it
//如果从热模块替换调用中间件,请忽略它
if (isHMR) { return }
// Get locale from params
const locale = params.lang || defaultLocale
if (!store.state.locales.includes(locale)) {
return error({ message: 'This page could not be found.', statusCode: 404 })
}
// Set locale
store.commit('SET_LANG', locale)
app.i18n.locale = store.state.locale
if(route.fullPath == '/') {
return redirect('/' + defaultLocale + '' + route.fullPath)
}
}
其他的配置都可以在 上面给出的官网链接中找到,这里就不在重复了