nuxt + element-ui +vue+ nuxt-i18n国际化

这里以中英文切换为例:

1. 安装 nuxt-i18n npm install nuxt-i18n -S

2.新建lang 文件夹,放置语言包

zh.js

const zh = {
index: '首页',
list:'列表'
}
export default zh

en.js

const en = {
index: 'Home',
list:'list'
}
export default en

3.新建i18n.js 配置文件

import zh from './lang/zh'
import en from './lang/en'
 
// 加载element-ui语言包
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
 
const mergeZH = Object.assign(zhLocale.default, zh);
const mergeEN = Object.assign(enLocale.default, en);
 
const I18N = {
  locales: [{
      code: 'en',
      iso: 'en-US',
      name: 'English'
    },
    {
      code: 'zh',
      iso: 'zh-ZH',
      name: '中文'
    }
  ],
  defaultLocale: 'zh',
  vueI18n: {
    fallbackLocale: 'zh',
    messages: {
      en: mergeEN,
      zh: mergeZH
    }
  }
}
 
export default I18N

4.添加中间件:lang.js,切换语言时,更改路由,同时更新store中语言类型

import getCookie from '@/config/get-cookie'
 
export default function ({store, route, redirect, req}) {
  const {lang} = getCookie(req)
  if (lang) {
    store.commit('setLang', lang)
  }
  const routePath = route.path
  if (store.state.lang === 'en' && routePath.indexOf(`/${store.state.lang}/`) === -1) {
    console.log('redirect')
    return redirect({path: `/${store.state.lang}${routePath}`, query: route.query})
  }
}

4. store中添加mutaion:

setLang(state, lang) {
        state.lang = lang
      }

5.在nuxt.config.js中配置module

import I18N from './config/i18n'
 
module.exports = {
 
  modules: [
    ['nuxt-i18n', I18N],
  ]
 
}

6. plugins/element-ui.js

import Vue from 'vue'
import Element from 'element-ui/lib/element-ui.common'
export default ({
  app
}) => {
  Vue.use(Element, {
    i18n: (key, value) => app.i18n.t(key, value)
  })
}

7.切换语言组件

<template>
  <span class="lang-switcher">
    <nuxt-link v-for="(locale, i) in showLocales" :key="i" :to="switchLocalePath(locale.code)">
      <span @click="handleChangeLang(locale.code)">点击切换{{ locale.name }}</span>
    </nuxt-link>
  </span>
</template>
 
<script>
const Cookie = process.client ? require("js-cookie") : undefined;
export default {
  name: "LangSwitcher",
  computed: {
    showLocales() {
      return this.$i18n.locales.filter(
        locale => locale.code !== this.$i18n.locale
      );
    }
  },
  methods: {
    handleChangeLang(lang) {
      this.$store.commit("setLang", lang);
      Cookie.set("lang", lang);
    }
  }
};
</script>

demo参考:https://github.com/liuzhumin/nuxt-demo.git

版权声明:除特别注明外,本站所有文章均为田珊珊个人博客原创

转载请注明:出处来自田珊珊个人博客 » nuxt + element-ui +vue+ nuxt-i18n国际化

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注