nuxt 国际化

637 阅读1分钟

1.安装vue-i18n

npm install vue-i18n --save  或 yarn add vue-i18n

2.在plugins文件夹中创建i18n.js

import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
export default ({ app, store }) => {
  let data = {};
  let Locale = store.state.locales;//获取语言环境 
  for (let i = 0; i < Locale.length; i++) { 
    data[Locale[i]] = require(`~/assets/locales/${Locale[i]}.json`);
  }//加载所有语言环境信息 
  app.i18n = new VueI18n({  
      locale: store.state.locale,//设置语言环境   
      fallbackLocale: 'zh',//预设的语言环境  
      messages: data, //设置语言环境信息 
      missing: (locale, key) => {
         if (key && key.indexOf('.') > -1) {
                let arr = key.split('.');
                if (arr[0] === 'message') {
                    return locale === 'zh' ? '参数错误' : 'Parameter error';
                }
          }
       }
  })  
  app.i18n.path = (link) => {   
      return `/${app.i18n.locale}/${link}` ;
  }
}

3.在middleware文件夹中创建routerConfig.js

export default function ({ isHMR, app, store, route, params, error, redirect }) { 
   const defaultLocale = app.i18n.fallbackLocale //获取预设语言   
   if (isHMR) return    
   const locale = params.lang || defaultLocale ;
    if (store.state.locales.indexOf(locale) === -1) {//判断路劲中是否有当前的语言环境      
        return error({ message: 'This page could not be found.', statusCode: 404 })   
     }    
    store.commit('SET_LANG', store.state.locale);
    app.i18n.locale = store.state.locale;    
    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, '/'))  
   } 
 }

4.在assets/locales文件夹中创建zh.json

{
    "zh":"中文"
}

5.在store/index.js文件夹新增

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

6.在nuxt.config.js配置

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

7.获取

$t('zh')

8.选择语言

this.$i18n.locale = name