nuxt-i18n 国际化

前言

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

创作不易,转载请注名出处。

原文博客(本人博客)地址:http://www.blog.geyunjie.com/2020/07/07/nuxt-i18n/

1、需求

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

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

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

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

3、安装vue-i18n

1npm install vue-i18n --save

2yarn add vue-i18n --save

4、在nuxt中引入vue-i18n

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

1importVuefrom'vue'

2importVueI18nfrom'vue-i18n'

3

4Vue.use(VueI18n)

5

6exportdefault({ app, store }) => {

7app.i18n =newVueI18n({

8    locale: store.state.locale,

9fallbackLocale:'zh-CN',// 我这里默认语言为中文

10    messages: {

11'en-US':require('@/locales/en-US.json'),

12'zh-CN':require('@/locales/zh-CN.json'),

13    },

14  })

15

16app.i18n.path =(link) =>{

17// 如果是默认语言,就省略

18if(app.i18n.locale === app.i18n.fallbackLocale) {

19return`/${link}`

20    }

21return`/${app.i18n.locale}/${link}`

22  }

23}

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

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

注意:

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

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

1exportconststate =()=>({

2locales: ['zh-CN','en-US'],

3locale:'',

4})

5

6exportconstmutations = {

7// 此处为设置locale

8  SET_LANG(state, locale) {

9if(state.locales.includes(locale)) {

10      state.locale = locale

11    }

12  },

13}

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

middleware中间件

1exportdefaultfunction({

2  isHMR,

3  app,

4  store,

5  route,

6  params,

7  error,

8  redirect,

9}){

10constdefaultLocale = app.i18n.fallbackLocale

11// If middleware is called from hot module replacement, ignore it

12if(isHMR)return

13// Get locale from params

14constlocale = params.lang || defaultLocale

15if(!store.state.locales.includes(locale)) {

16returnerror({message:'This page could not be found.',statusCode:404})

17  }

18// Set locale

19store.commit('SET_LANG', locale)

20  app.i18n.locale = store.state.locale

21// If route is /<defaultLocale>/... -> redirect to /...

22if(

23    locale === defaultLocale &&

24route.fullPath.indexOf('/'+ defaultLocale) ===0

25  ) {

26consttoReplace =

27'^/'+

28      defaultLocale +

29(route.fullPath.indexOf('/'+ defaultLocale +'/') ===0?'/':'')

30constre =newRegExp(toReplace)

31returnredirect(route.fullPath.replace(re,'/'))

32  }

33}

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

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

1exportdefault{

2/*

3  ** Nuxt rendering mode

4  ** See https://nuxtjs.org/api/configuration-mode

5  */

6mode:'universal',

7/*

8  ** Nuxt target

9  ** See https://nuxtjs.org/api/configuration-target

10  */

11target:'server',

12/*

13  ** Headers of the page

14  ** See https://nuxtjs.org/api/configuration-head

15  */

16  head: {

17title: process.env.npm_package_name ||'',

18    meta: [

19{charset:'utf-8'},

20{name:'viewport',content:'width=device-width, initial-scale=1'},

21      {

22hid:'description',

23name:'description',

24content: process.env.npm_package_description ||'',

25      },

26    ],

27    link: [

28{rel:'icon',type:'image/x-icon',href:'/favicon.ico'},

29      {

30rel:'stylesheet',

31href:'//at.alicdn.com/t/xxx.css',

32      },

33    ],

34// 头部内容、

35  },

36/*

37  ** Global CSS

38  */

39css: ['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  */

61components: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  */

72modules: ['@nuxtjs/axios'],

73/**

74  * axios 代理

75  */

76  axios: {

77prefix:'/api',

78credentials:true,

79proxy:true,

80  },

81  proxy: {

82'/api': {

83target:'xxxx',

84      pathRewrite: {

85'^/api/':'/',

86      },

87changeOrigin: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: {

99vendor: ['element-ui'],

100    babel: {

101      plugins: [

102        [

103'component',

104          {

105libraryName:'element-ui',

106styleLibraryName:'theme-chalk',

107          },

108        ],

109      ],

110comments: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

<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

<script>

import Index from '@/pages/_lang/index'

export default Index

</script>

10、总结

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

运行结果

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

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

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

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

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

让我们共同加油吧!!!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335