vue-i18n example

This commit is contained in:
Sébastien Chopin 2017-02-08 18:49:16 +01:00
parent 27336d4741
commit f490786fa3
10 changed files with 66 additions and 17 deletions

View File

@ -0,0 +1,7 @@
export default async function ({ store, params, error }) {
const lang = params.lang || 'en'
if (!store.state.lang.locales.includes(lang)) {
return error({ message: 'Page not found', statusCode: 404 })
}
return store.dispatch('lang/setLang', lang)
}

View File

@ -1,7 +0,0 @@
// import Vue from 'vue'
export default function ({ params }) {
console.log(params)
// if (params)
// Vue.config.lang = 'en'
}

View File

@ -1,6 +1,9 @@
module.exports = {
build: {
vendor: ['vue-i18n']
router: {
middleware: 'i18n'
},
plugins: ['~plugins/vue-i18n']
build: {
vendor: ['axios']
},
plugins: ['~plugins/i18n']
}

View File

@ -1,3 +1,7 @@
<template>
<p v-html="$t('message.welcome')"></p>
<div>
<p>{{ $t('message.welcome') }}</p>
<nuxt-link to="/fr">French</nuxt-link>
<nuxt-link to="/">English</nuxt-link>
</div>
</template>

View File

@ -0,0 +1,9 @@
import axios from 'axios'
let options = {}
// The server-side needs a full url to works
if (process.SERVER_BUILD) {
options.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}`
}
export default axios.create(options)

View File

@ -0,0 +1,12 @@
import Vue from 'vue'
import store from '~store'
Vue.prototype.$t = function (key) {
const state = store.state.lang
let keys = key.split('.')
let value = state._[state.lang]
keys.forEach((k) => {
value = value[k]
})
return value
}

View File

@ -1,6 +0,0 @@
import Vue from 'vue'
if (process.BROWSER_BUILD) {
var VueI18n = require('vue-i18n')
Vue.use(VueI18n)
}

View File

@ -0,0 +1,27 @@
import axios from '~plugins/axios'
export const state = {
locales: ['en', 'fr'], // available langages
lang: null, // current lang
_: {} // store for translations
}
export const mutations = {
SET_LANG (state, lang) {
state.lang = lang
},
SET_TRANSLATION (state, translation) {
state._[state.lang] = translation
}
}
export const actions = {
async setLang ({ state, commit }, lang) {
if (state._[lang]) {
return commit('SET_LANG', lang)
}
let res = await axios.get(`/locales/${lang}.json`)
commit('SET_LANG', lang)
commit('SET_TRANSLATION', res.data)
}
}