Nuxt.js+i18n 国际化

一、安装vue-i18n

npm install vue-i18n  或  yarn add vue-i18n

二、在store文件夹下更新index.js文件

export const state = () => ({
  locales: ["en", "zh"],
  locale: "zh"
});

export const mutations = {
  SET_LANG(state, locale) {
    if (state.locales.includes(locale)) {
      state.locale = locale;
    }
  }
};

三、在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',
    messages: {
      zh: require('~/locales/zh.json'),
      en: require('~/locales/en.json')
    }
  })

  app.i18n.path = (link) => {
    if (app.i18n.locale === app.i18n.fallbackLocale) {
      return `/${link}`
    }

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

四、在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.includes(locale)) {
    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, '/'))
  }
}

五、增加locales文件夹

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

六、配置nuxt.config.js文件

在配置中添加这两句代码,重新运行才生效。

 router: {
    middleware: 'i18n'
  },
 plugins: ['@/plugins/i18n.js'],

 七、创建_lang文件夹

在pages文件夹下新建_lang文件夹,之后在此文件夹下新建对应的页面组件。一定要带下划线的_lang,否则params.lang,获取不到值。

八、在pages文件夹下相应的页面应用

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

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

以上纯粹个人理解,若有问题,望告知。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值