Vue SSR Nuxt 國際化

安裝

$ npm install vue-i18n --save
複製代碼

使用

~/nuxt.config.js

引入插件,啓動中間件javascript

plugins: ['~/plugins/i18n.js'],
router: {
  middleware: 'i18n',
}
複製代碼

~/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(`~/locales/${Locale[i]}.json`)
  }
  // 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',
    messages: data
  })
	// 自定義頁面跳轉方法
  app.i18n.path = (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.indexOf(locale) === -1) {
    return error({ message: 'This page could not be found.', statusCode: 404 })
  }
  // Set locale
  store.commit('SET_LANG', store.state.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/index.js

建立本地語言庫vue

export default () => {
  return ['en', 'fr', 'cn']
}
複製代碼

~/locales/fr.json

更加不一樣頁面添加不用的語言java

{
  "links": {
    "home": "Accueil",
    "about": "À propos",
    "english": "Version Anglaise",
    "french": "Version Française"
  },
  "home": {
    "title": "Bienvenue",
    "introduction": "Ceci est un texte d'introduction en Français."
  },
  "about": {
    "title": "À propos",
    "introduction": "Cette page est faite pour vous donner plus d'informations."
  }
}
複製代碼

~/store/index.js

import Locale from '~/locales'

export const state = () => ({
  locales: Locale(),
  locale: Locale()[0]
})

export const mutations = {
  SET_LANG(state, locale) {
    if (state.locales.indexOf(locale) !== -1) {
	  	console.log(locale)
      state.locale = locale
    }
  }
}
複製代碼

方法

獲取

$t('links.english')
複製代碼

設置

this.$i18n.locale = name
複製代碼
相關文章
相關標籤/搜索