dkfbasel / vuex-i18n

Localization plugin for vue.js 2.0 using vuex as store
MIT License
666 stars 56 forks source link

this.$i18n returns undefined #77

Closed ll931217 closed 6 years ago

ll931217 commented 6 years ago

Hello,

As the title says, the global object this.$i18n is returning undefined.

Here is my main.js file:

import Vue from 'vue'
import Vuetify from 'vuetify'
import axios from 'axios'
import VueAxios from 'vue-axios'
import VueHead from 'vue-head'
import VuexI18n from 'vuex-i18n'

import App from './App.vue'
import router from './router'
import store from './store'
import enUS from './locales/enUS.js'
import zhTW from './locales/zhTW.js'

import 'vuetify/dist/vuetify.css'

const axiosInstance = axios.create({
  baseURL: process.env.SERVER_ENDPOINT || 'http://localhost:3020',
  headers: {'Content-Type': 'application/json'}
})

Vue.use(Vuetify)
Vue.use(VueAxios, axiosInstance)
Vue.use(VueHead)
Vue.use(VuexI18n.plugin, store)

Vue.config.productionTip = false

Vue.i18n.add('zhTW', zhTW)
Vue.i18n.add('enUS', enUS)

Vue.i18n.set('zhTW')

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

In my App.vue file I have the following to check if this.$i18n is defined:

export default {
    methods: {
        change: key => {
            console.log('i18n:', this.$i18n)
        }
    }
}

Anyone have an idea why this.$i18n is undefined?

tikiatua commented 6 years ago

Hi @ll931217

A quick idea: I think this could be due to the use of an arrow function with the change method in your app component. Arrow functions change the this context to the current closure. Therefore this.$i18n would not point the vue component instance anymore.

Could you try to change the method to:

export default {
    methods: {
        change(key) {
            console.log('i18n:', this.$i18n)
        }
    }
}
ll931217 commented 6 years ago

@tikiatua Hello, seems that like fixed the problem. Just learnt something new about the arrow functions, thank you!