nuxtjs国际化

2019-11-22T14:39:41.732 | 浏览:12 | 文章类别: 前端

nuxtjs中使用i18n

1. 安装 vue-i18n

npm install vue-i18n --save

2. 在nuxtjs 中引入vue-i18n

在 ~/plugins文件夹下新建 i18n.js, 并键入以下代码:

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default ({ app, store }) => {
    // Set i18n instance on app
    // This way we can use it in middleware and pages asyncData/fetch
    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}`
    }
}

3. 在vuex中保存当前语言状态

在 ~/store文件夹下 新建 index.js文件,键入以下代码:

export const state = () => ({
    locales: ['en-US', 'zh-CN'],
    locale: 'zh-CN'
})

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

4. 在~/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.indexOf(locale) === -1) {
        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, '/')
        )
    }
}

5. 修改nuxt.config.js文件配置如下:

  router: {
    middleware: 'i18n'
  },
  plugins: [
    '@/plugins/i18n.js',
    // '@/plugins/iview'
  ],
    generate: {
    // 这里可能是指定路由
    routes: ['/', '/about', '/zh-CN', '/zh-CN/about']
  },

6. 创建本地语言包

新建 local文件夹,创建en-US.json, zh-CN.json两个文件 zh-CN.json

{
    "links": {
        "english": "简体中文",
    },
    "home": {
        "index": "首页",
        "search": "搜索"
    },
    "about": {
        "title": "关于",
    }
}

en-US.json

{
    "links": {
        "home": "Home",
        "about": "About",
        "english": "English",
    },
    "home": {
        "index": "index",
        "search": "searchs"
    },
    "about": {
        "title": "About",
    }
}

7. page文件夹下创建文件

page/_lang/index.vue

<template>
  <b-container class="bv-example-row main">
    <b-row>
      <b-col md="8">
        <NuxtLink v-if="$i18n.locale === 'zh-CN'" :to="`/en-US` + $route.fullPath" class="Header__Link" active-class="none" exact>
            en{{ $t('links.english') }}
          </NuxtLink>
          <NuxtLink v-else :to="$route.fullPath.replace(/^\/[^\/]+/, '')" class="Header__Link" active-class="none" exact>
            zh{{ $t('links.english') }}
          </NuxtLink>
        <div>
        </div>
      </b-col>

    </b-row>
  </b-container>
</template>

<script>
export default {
  components: {},
  methods:{
    changelang(){
      SET_LANG('zh-CN')
    },
  }
};
</script>

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

page/index.vue

<script>
import Index from '~/pages/_lang/index'
export default Index
</script>

切换语言:

 <NuxtLink v-if="$i18n.locale === 'zh-CN'" :to="`/en-US` + $route.fullPath" class="Header__Link" active-class="none" exact>
            en{{ $t('links.english') }}
</NuxtLink>
<NuxtLink v-else :to="$route.fullPath.replace(/^\/[^\/]+/, '')" class="Header__Link" active-class="none" exact>
            zh{{ $t('links.english') }}
</NuxtLink>

切换这里,还没弄懂咋回事, 跳转链接后怎么保持这些问题

最后, 默认显示这样: 在这里插入图片描述 点击enenglish 切换成英文后: 在这里插入图片描述

基本就这样,明天再研究一下,会持续更新!