nuxt.js實戰之用vue-i18n實現多語言
阿新 • • 發佈:2018-11-13
一、實現步驟
1、安裝vue-i18n並且建立store.js(vuex狀態管理)檔案
2、建立一個(middleware)中介軟體,用來管理不同的語言
3、建立不同語言的json檔案作為語言包(例如: ~locales/en.json)
4、在pages資料夾下建立檔案,並進行翻譯
二、詳細步驟
1、安裝vue-i18n
npm install vue-i18n --save
2、在nuxt應用程式中引入vue-i18n
新建檔案 ~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', messages: { 'en': require('~/locales/en.json'), 'fr': require('~/locales/fr.json') } }); app.i18n.path = (link) => { if (app.i18n.locale === app.i18n.fallbackLocale) { return `/${link}`; } return `/${app.i18n.locale}/${link}`; } }
3、使用vuex儲存當前語言狀態
新建檔案~store/index.js,內容如下:
export const state = () => ({ locales: [‘en’, ‘fr’], locale: ‘en’ }) export const mutations = { SET_LANG(state, locale) { if (state.locales.indexOf(locale) !== -1) { state.locale = locale } } }
4、在middleware下新建i18n.js用來控制語言切換
/* * 1. sets i18n.locale and state.locale if possible * 2. redirects if not with locale */ export default function ({ isHMR, app, store, route, params, error, redirect }) { if (isHMR) { // ignore if called from hot module replacement return; } // if url does not have language, redirect to english else if (!params.lang) { return redirect('/en'+route.fullPath); } // based on directory structure _lang/xxxx, en/about has params.lang as "en" const locale = params.lang || 'en'; store.commit('SET_LANG', locale); // set store app.i18n.locale = store.state.locale; }
5、修改nuxt.config.js檔案配置如下:
module.exports = { loading: { color: '#3B8070' }, build: { // customize webpack build vendor: ['vue-i18n'] // webpack vue-i18n.bundle.js }, router: { // customize nuxt.js router (vue-router). middleware: 'i18n' // middleware all pages of the application }, plugins: ['~/plugins/i18n.js'], // webpack plugin generate: { routes: ['/', '/about', '/fr', '/fr/about'] } }
6、建立本地語言包
例如:(~locales/en.js)
{ "links": { "home": "Home", ... }, "home": { "title": "Welcome", "introduction": "This is an introduction in English." }, "about": { "title": "About", "introduction": "..." } }
(~locales/fr.js)
{ "links": { "home": "Accueil", ... }, "home": { "title": "Bienvenue", "introduction": "Ceci est un texte d'introduction en Français." }, "about": { "title": "À propos", "introduction": "..." } }
7、建立頁面,並新增翻譯
~pages/_lang/index.vue
~pages/_lang/about.vue
<template> <div class="Content"> <div class="container"> <h1 class="Content__Title">{{ $t('about.title') }}</h1> <p>{{ $t('about.introduction') }}</p> </div> </div> </template> <script> export default { head() { return { title: this.$t('about.title') } } } </script>