1、實現步驟javascript
一、安裝vue-i18n而且建立store.js(vuex狀態管理)文件vue
二、建立一個(middleware)中間件,用來管理不一樣的語言java
三、建立不一樣語言的json文件做爲語言包(例如: ~locales/en.json)webpack
四、在pages文件夾下建立文件,並進行翻譯web
2、詳細步驟vue-router
一、安裝vue-i18nvuex
npm install vue-i18n --save
二、在nuxt應用程序中引入vue-i18nnpm
新建文件 ~plugins/i18n.js,內容以下:json
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}`; } }
三、使用vuex保存當前語言狀態app
新建文件~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 } } }
四、在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; }
五、修改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'] } }
六、建立本地語言包
例如:(~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": "..." } }
七、建立頁面,並添加翻譯
~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>