nuxt-i18n 國際化

前言

? 由于本人的能力有限,如若有說得做的不對的地方,還望指出。當然,如若你有更好的方法,或者更優(yōu)解,還望不吝賜教。

創(chuàng)作不易,轉(zhuǎn)載請注名出處。

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

1、需求

根據(jù)需求,現(xiàn)在需要做一個服務端渲染的PC網(wǎng)站。SSR

技術(shù)選型:Vue Vue-i18n Nuxt.js elementUI

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

首先說一下,nuxt.js和我們之前做的SPA單頁面應用不一樣,做國際化也不一樣,之前已經(jīng)寫過在SPA中如何使用國際化,現(xiàn)在再寫一下在SSR中如何使用國際化

3、安裝vue-i18n

1npm install vue-i18n --save

2yarn add vue-i18n --save

4、在nuxt中引入vue-i18n

在plugins文件夾下創(chuàng)建一個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中保存語言的狀態(tài)

在store頁面下創(chuàng)建一個index.js文件

注意:

? nuxt.js中如果想要使用vuex的模塊化功能,需要使用如下方法,nuxt會自動生成模塊化的vuex。

? 如果不實用模塊化,則和vuex的使用沒有任何區(qū)別

1exportconststate =()=>({

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

3locale:'',

4})

5

6exportconstmutations = {

7// 此處為設(shè)置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// 頭部內(nèi)容、

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// 這里是指定生成靜態(tài)文件的路由

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、創(chuàng)建本地語言包

? 根據(jù)自己不同的需求,創(chuàng)建不同的語言包,這里只展示一個語言包

? 新建 local文件夾,創(chuàng)建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文件夾下創(chuàng)建頁面文件

在page頁面文件夾下創(chuàng)建_lang文件夾。lang前面的下劃線是動態(tài)路由的意思,nuxt.js的router路由文件會根據(jù)page文件夾自動生成對應的路由文件

下面代碼是切換語言的文件代碼

創(chuàng)建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>

創(chuàng)建page/index.vue

<script>

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

export default Index

</script>

10、總結(jié)

到此 國際化就配置完成了。

運行結(jié)果

默認語言URL:http://localhost:3000

非默認語言URL:http://localhost:3000/en-US

如果能夠幫助到你,是小編最大的榮幸

當然 有 不好的地方 請大家?guī)兔χ赋?學習永無止境

小編一直認為 人外有人 天外有天 一起學習 共同進步

讓我們共同加油吧!?。?/p>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容