官網案例 https://zh.nuxtjs.org/examples/i18n/#codefund_ad給的例子是pages文件夾下 默認語言頁面和其他語言頁面分開路徑放置
// 1悠咱、安裝多語言
yarn install vue-i18n
//2、增加文件,作為第三方插件
// plugins/i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '~/locales/index.js'
Vue.use(VueI18n)
export default ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: store.state.locale || 'zh',
messages: messages
})
/* 路徑轉換調用方法 .趟章,可在頁面調用轉換路徑 */
app.i18n.path = link => {
/*
此情況默認語言不用加lang參數,是官網的案列 钧唐,本人是將頁面都放在_lang文件夾下生宛,所以此段代碼注釋
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
} */
return `/${app.i18n.locale}/${link}`
}
}
// 3、nuxt.config.js 配置插件
plugins: [
{ src: '~/plugins/i18n.js' }
],
// 4闷叉、配置中間件做一些處理
// middleware / i18n.js
// 在每個路由改變時被調用 nuxt.config.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 || store.state.locale || defaultLocale
//不存在該多語言的錯誤頁面跳轉
if (store.state.locales.indexOf(locale) === -1) {
return error({
message: 'This language could not be found.',
statusCode: 404
})
}
// 路由初始化重定向
if (route.fullPath === '/') { // ‘/’是路由文件的base值
return redirect('/' + store.state.locale + '' + route.fullPath)
}
// Set locale
// 需注意 ,vuex 頁面刷新后狀態(tài)將不再保存脊阴,若需保存握侧,可使用localstorage
store.commit('SET_LANG', locale)
app.i18n.locale = store.state.locale
}
//5、 中間件配置
/* i18n中間件在每個路由改變時被調用 */
router: {
middleware: ['i18n', 'route']
},
// 6嘿期、多語言設置
// locales/index.js
import home from './home'
import common from './common'
export default _.merge(
home,
common
)
//common.js
export default {
zh: {
nav: {
//header
home: '首頁',
service: '服務',
price: '價格',
},
//footer
footer: {
about: '關于CCloud',
},
error: {
info: '抱歉品擎,頁面無法訪問',
backHome: '返回首頁'
}
},
en: {
nav: {
//header
home: 'Home',
service: 'Service',
price: 'Price',
},
//footer
footer: {
about: 'About CCloud'
},
error: {
info: 'Sorry, the page is inaccessible',
backHome: 'Back to home'
}
}
}