Hi everyone, I am having a problem with 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': store.state.en,
'fr': store.state.fr
}
})
}
page/ _lang/index.vue
<template>
<div class="Content">
<div class="container">
<h1 class="Content__Title">{{ $t('home.title') }}</h1>
<p>{{ $t('home.introduction') }}</p>
</div>
</div>
</template>
<script>
export default {
async fetch({app,store}) {
await store.dispatch('GET_DATA')
},
head() {
return { title: this.$t('home.title') }
}
}
</script>
store/index.js
import axios from 'axios'
axios.defaults.baseURL = 'http://127.0.0.1:3021/api'
export const state = () => ({
locales: ['en', 'fr'],
locale: 'en',
en: {},
fr: {}
})
export const mutations = {
SET_LANG(state, locale) {
if (state.locales.indexOf(locale) !== -1) {
state.locale = locale
}
},
SET_DATA(state,data) {
if(state.locale === 'en') {
state.en = data
}else if(state.locale === 'fr'){
state.fr = data
}
}
}
export const actions = {
async GET_DATA({commit,state}) {
const { data } = await axios.get('/indexInit',{
headers: {
language: state.locale
}
})
commit('SET_DATA',data)
}
}
The fetch method is executed before the route changes, but in i18.js middleware, it takes a route change to execute SET_LANG
. It needs to get the params lang in the params, which are contradictory to each other. How to solve this problem?