zoukankan      html  css  js  c++  java
  • Nuxt.js国际化vue-i18n的搭配使用

    Nuxt.js国际化的前提是,已经使用脚手架工具搭建好了Nuxt.js的开发环境。
    我使用的环境是nuxt@2.3 + vuetify@1.4 + vue-i18n@7.3

    1. 先安装vue-i18n

    npm install --save vue-i18n
    

    2. 更新store文件

    在@/store/index.js文件中,修改添加如下代码:

    export const state = () => ({
      locales: ['en-US', 'zh-CN'],
      locale: 'en-US'
    })
    
    export const mutations = {
      SET_LANG(state, locale) {
        if (state.locales.indexOf(locale) !== -1) {
          state.locale = locale
        }
      }
    }
    

    注意,是mutations对象下的SET_LANG函数

    3. 更新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: 'en-US',
        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}`
      }
    }
    
    

    messages对象的key要和state.locales中的相同

    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. 增加locales文件夹

    增加对应语言的对照json数据,en-US.json、zh-CN.json等等
    其中,两个json数据,需要相同的key,才能翻译成功。

    {
      "links": {
        "home": "Home",
        "about": "About",
        "english": "English version",
        "chinese": "简体中文"
      },
      "home": {
        "title": "Welcome",
        "introduction": "This is an introduction in English."
      },
      "about": {
        "title": "About",
        "introduction": "This page is made to give you more informations."
      }
    }
    
    

    6. 修改nuxt.config.js文件

    修改或者增加如下对象:

      router: {
        middleware: 'i18n'
      },
      plugins: ['@/plugins/i18n.js'],
      generate: {
        routes: ['/', '/about', '/zh-CN', '/zh-CN/about']
      }
    

    7. 修改pages文件夹下相应的页面

    在pages文件夹下新建_lang文件夹,之后在此文件夹下新建对应的页面组件。
    例如:
    @/pages/_lang/index.vue
    @/pages/_lang/about.vue
    一定要带下划线的_lang,否则params.lang,获取不到值。可以参考官网这里

    <template >
        <div> {{ $t('home.title') }}</div>
    </template>
    

    页面中的需要翻译的内容,都使用语法$t('')给包裹起来,其中里面的值,是从@/locales/***.json文件中获取对应的key

    8. 总结

    经过以上7个步骤之后,国际化基本可以完成了。完成国际化的过程中,提到了三个需求

    1. 切换语言,不刷新页面。【只需要在切换的时候,设置store中的locale值为对应的language值,不做其他操作】
    2. 刷新页面之后,还是当前语言。【这个需要将设置好的语言保存起来,放到本地缓存中,是个不错的选择】
    3. 根据浏览器的语言,显示语言。【使用navigator.language来获取浏览器默认语言,之后将其赋值给为store中的locale值】

    2、3的优先级,首次进来,根据浏览器系统语言决定,刷新的时候,根据缓存决定。最后都需要给store中的locale赋值。显示何种语言,是由$i18n.locale决定。

    参考案例

    1. nuxt官网示例
  • 相关阅读:
    所有问题都可以通过增加一层来解决
    open一个页面并关闭父页(小技巧)
    <%=字符串%>回刷技巧(小技巧)
    轮环(Ouroboros)世界观介绍,摘自Guide Book
    windows7下MSN如何最小化到任务栏
    触发器权限
    网页GZIP压缩
    iis6配置使用页面Gzip压缩提速
    唉,被删的帖
    创建型模式,结构型模式,结构型模式
  • 原文地址:https://www.cnblogs.com/weiqinl/p/10581867.html
Copyright © 2011-2022 走看看