Skip to content

Instantly share code, notes, and snippets.

@hmsk
Last active March 1, 2018 06:20
Show Gist options
  • Save hmsk/73e2b8de8f323751629a04e1504519da to your computer and use it in GitHub Desktop.
Save hmsk/73e2b8de8f323751629a04e1504519da to your computer and use it in GitHub Desktop.
I18n in Nuxt.js
<!-- 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>
<!-- pages/about.vue -->
<!-- This page is totally annoying -->
<script>
import About from '~/pages/_lang/about'
export default About
</script>
// middleware/i18n.js
export default function ({ isHMR, app, store, route, params, error, redirect }) {
// If middleware is called from hot module replacement, ignore it
if (isHMR) return
// Get locale from params
const locale = params.lang || 'en'
if (store.state.locales.indexOf(locale) === -1) {
return error({ message: 'This page could not be found.', statusCode: 404 })
}
// Set locale
store.commit('SET_LANG', locale)
app.i18n.locale = store.state.locale
// If route is /en/... -> redirect to /...
if (locale === 'en' && route.fullPath.indexOf('/en') === 0) {
return redirect(route.fullPath.replace(/^\/en/, '/'))
}
}
// nuxt.config.js
module.exports = {
build: {
vendor: ['vue-i18n']
},
router: {
middleware: 'i18n'
},
plugins: ['~/plugins/i18n.js'],
generate: {
routes: ['/', '/about', '/ja', '/ja/about'] // REPEAT EACH LANG!?
}
}
// plugins/i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import en from '~/locales/en.yaml'
import ja from '~/locales/ja.yaml'
Vue.use(VueI18n)
export default ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'en',
messages: {
en, ja
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment