前言

​ 由于本人的能力有限,如若有说得做的不对的地方,还望指出。当然,如若你有更好的方法,或者更优解,还望不吝赐教。

1、需求

根据需求,现在需要做一个服务端渲染的PC网站。SSR

技术选型:Vue Vue-i18n Nuxt.js elementUI

2、对于Vue-i8n在Nuxt.js中的使用

首先说一下,nuxt.js和我们之前做的SPA单页面应用不一样,做国际化也不一样,之前已经写过在SPA中如何使用国际化,现在再写一下在SSR中如何使用国际化

3、安装vue-i18n

1
2
npm install vue-i18n --save
yarn add vue-i18n --save

4、在nuxt中引入vue-i18n

在plugins文件夹下创建一个i18n.js文件,并写入如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'zh-CN', // 我这里默认语言为中文
messages: {
'en-US': require('@/locales/en-US.json'),
'zh-CN': require('@/locales/zh-CN.json'),
},
})

app.i18n.path = (link) => {
// 如果是默认语言,就省略
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}

5、在vuex中保存语言的状态

在store页面下创建一个index.js文件

注意:

​ nuxt.js中如果想要使用vuex的模块化功能,需要使用如下方法,nuxt会自动生成模块化的vuex。

​ 如果不实用模块化,则和vuex的使用没有任何区别

1
2
3
4
5
6
7
8
9
10
11
12
13
export const state = () => ({
locales: ['zh-CN', 'en-US'],
locale: '',
})

export const mutations = {
// 此处为设置locale
SET_LANG(state, locale) {
if (state.locales.includes(locale)) {
state.locale = locale
}
},
}

6、在middleware文件夹下新建i18n.js文件用来控制语言的切换

middleware中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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 is /<defaultLocale>/... -> redirect to /...
if (
locale === defaultLocale &&
route.fullPath.indexOf('/' + defaultLocale) === 0
) {
const toReplace =
'^/' +
defaultLocale +
(route.fullPath.indexOf('/' + defaultLocale + '/') === 0 ? '/' : '')
const re = new RegExp(toReplace)
return redirect(route.fullPath.replace(re, '/'))
}
}

7、在nuxt.config.js文件中进行配置

在上面写好之后,需要在这里进行配置才可以使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
export default {
/*
** Nuxt rendering mode
** See https://nuxtjs.org/api/configuration-mode
*/
mode: 'universal',
/*
** Nuxt target
** See https://nuxtjs.org/api/configuration-target
*/
target: 'server',
/*
** Headers of the page
** See https://nuxtjs.org/api/configuration-head
*/
head: {
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || '',
},
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{
rel: 'stylesheet',
href: '//at.alicdn.com/t/xxx.css',
},
],
// 头部内容、
},
/*
** Global CSS
*/
css: ['element-ui/lib/theme-chalk/index.css', '@/assets/public.less'],
/*
** Plugins to load before mounting the App
** https://nuxtjs.org/guide/plugins
*/
plugins: [
{ src: '@/plugins/element-ui', ssr: true },
'~/plugins/axios',
+ '@/plugins/i18n.js',
],

router: {
+ middleware: 'i18n',
},
generate: {
// 这里是指定生成静态文件的路由
+ routes: ['/', '/about', '/zh-CN', '/zh-CN/about'],
},
/*
** Auto import components
** See https://nuxtjs.org/api/configuration-components
*/
components: true,
/*
** Nuxt.js dev-modules
*/
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
'@nuxtjs/eslint-module',
],
/*
** Nuxt.js modules
*/
modules: ['@nuxtjs/axios'],
/**
* axios 代理
*/
axios: {
prefix: '/api',
credentials: true,
proxy: true,
},
proxy: {
'/api': {
target: 'xxxx',
pathRewrite: {
'^/api/': '/',
},
changeOrigin: true,
},
},
/*
** Build configuration
** See https://nuxtjs.org/api/configuration-build/
*/
// build: {
// transpile: [/^element-ui/],

// },
build: {
vendor: ['element-ui'],
babel: {
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
],
comments: true,
},
},
}

8、创建本地语言包

​ 根据自己不同的需求,创建不同的语言包,这里只展示一个语言包

​ 新建 local文件夹,创建en-US.json文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"links": {
"home": "Home",
"about": "About",
"english": "English"
},
"home": {
"index": "index",
"search": "searchs",
"title": "hahah"
},
"about": {
"title": "About"
}
}

9、在page文件夹下创建页面文件

在page页面文件夹下创建_lang文件夹。lang前面的下划线是动态路由的意思,nuxt.js的router路由文件会根据page文件夹自动生成对应的路由文件

下面代码是切换语言的文件代码

创建page/_lang/index.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
<el-container class="bv-example-row main">
<NuxtLink
v-if="$i18n.locale === 'zh-CN'"
:to="{ name: 'lang', params: { lang: 'en-US' } }"
class="Header__Link"
active-class="none"
exact
>
en{{ $t('links.english') }}
</NuxtLink>

<NuxtLink
v-else
:to="{ name: 'lang', params: { lang: 'zh-CN' } }"
class="Header__Link"
active-class="none"
exact
>
zh{{ $t('links.english') }}
</NuxtLink>
<p>{{ $route.fullPath }}</p>
</el-container>
</template>

<script>
export default {
head() {
return { title: this.$t('home.title') }
},
components: {},
created() {
console.log(this)
},
}
</script>

<style scoped>
.main {
margin: 30px auto;
}
</style>

创建page/index.vue

1
2
3
4
<script>
import Index from '@/pages/_lang/index'
export default Index
</script>

10、总结

到此 国际化就配置完成了。

运行结果

1

默认语言URL:http://localhost:3000

非默认语言URL:http://localhost:3000/en-US

如果能够帮助到你,是小编最大的荣幸

当然 有 不好的地方 请大家帮忙指出 学习永无止境

小编一直认为 人外有人 天外有天 一起学习 共同进步

让我们共同加油吧!!!

程序的世界,写作的过程中部分文章难免会参考与借鉴网络上的一些资源、见解。如有侵权请与作者联系。如若如实侵权,文章会在24小时内删除。如若由于部分文章存在侵权行为给您带来不便还请见谅。

本博客仅仅为自己以及前端爱好者提供便利,不做任何商业用途。