前言

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

1、需求

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

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

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

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

3、安装vue-i18n

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

4、在nuxt中引入vue-i18n

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

1
import Vue from 'vue'
2
import VueI18n from 'vue-i18n'
3
4
Vue.use(VueI18n)
5
6
export default ({ app, store }) => {
7
  app.i18n = new VueI18n({
8
    locale: store.state.locale,
9
    fallbackLocale: 'zh-CN', // 我这里默认语言为中文
10
    messages: {
11
      'en-US': require('@/locales/en-US.json'),
12
      'zh-CN': require('@/locales/zh-CN.json'),
13
    },
14
  })
15
16
  app.i18n.path = (link) => {
17
    // 如果是默认语言,就省略
18
    if (app.i18n.locale === app.i18n.fallbackLocale) {
19
      return `/${link}`
20
    }
21
    return `/${app.i18n.locale}/${link}`
22
  }
23
}

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

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

注意:

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

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

1
export const state = () => ({
2
  locales: ['zh-CN', 'en-US'],
3
  locale: '',
4
})
5
6
export const mutations = {
7
  // 此处为设置locale
8
  SET_LANG(state, locale) {
9
    if (state.locales.includes(locale)) {
10
      state.locale = locale
11
    }
12
  },
13
}

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

middleware中间件

1
export default function ({
2
  isHMR,
3
  app,
4
  store,
5
  route,
6
  params,
7
  error,
8
  redirect,
9
}) {
10
  const defaultLocale = app.i18n.fallbackLocale
11
  // If middleware is called from hot module replacement, ignore it
12
  if (isHMR) return
13
  // Get locale from params
14
  const locale = params.lang || defaultLocale
15
  if (!store.state.locales.includes(locale)) {
16
    return error({ message: 'This page could not be found.', statusCode: 404 })
17
  }
18
  // Set locale
19
  store.commit('SET_LANG', locale)
20
  app.i18n.locale = store.state.locale
21
  // If route is /<defaultLocale>/... -> redirect to /...
22
  if (
23
    locale === defaultLocale &&
24
    route.fullPath.indexOf('/' + defaultLocale) === 0
25
  ) {
26
    const toReplace =
27
      '^/' +
28
      defaultLocale +
29
      (route.fullPath.indexOf('/' + defaultLocale + '/') === 0 ? '/' : '')
30
    const re = new RegExp(toReplace)
31
    return redirect(route.fullPath.replace(re, '/'))
32
  }
33
}

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

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

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

8、创建本地语言包

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

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

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

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

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

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

创建page/_lang/index.vue

1
<template>
2
  <el-container class="bv-example-row main">
3
    <NuxtLink
4
      v-if="$i18n.locale === 'zh-CN'"
5
      :to="{ name: 'lang', params: { lang: 'en-US' } }"
6
      class="Header__Link"
7
      active-class="none"
8
      exact
9
    >
10
      en{{ $t('links.english') }}
11
    </NuxtLink>
12
13
    <NuxtLink
14
      v-else
15
      :to="{ name: 'lang', params: { lang: 'zh-CN' } }"
16
      class="Header__Link"
17
      active-class="none"
18
      exact
19
    >
20
      zh{{ $t('links.english') }}
21
    </NuxtLink>
22
    <p>{{ $route.fullPath }}</p>
23
  </el-container>
24
</template>
25
26
<script>
27
export default {
28
  head() {
29
    return { title: this.$t('home.title') }
30
  },
31
  components: {},
32
  created() {
33
    console.log(this)
34
  },
35
}
36
</script>
37
38
<style scoped>
39
.main {
40
  margin: 30px auto;
41
}
42
</style>
43

创建page/index.vue

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

10、总结

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

运行结果

1

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

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

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

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

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

让我们共同加油吧!!!

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

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