I'm building a vua/laravel application that should be available in multiple languages. I have all files defined in my language files, and am able to use them in blade templates, but I'm having a hard time using them in my vue components.
I found a good package for it: https://github.com/kg-bot/laravel-localization-to-vue
Installed it and configured it. I then added this to my bootstrap.js, since that seems to be the most logical place for it:
window.messages = axios.get('http://localhost:8083/js/localization.js')
I see that the ajax call is performed and the response contains proper JSON
I then added this to my main blade template:
<script>
window.default_locale = "{{ config('app.locale') }}";
window.fallback_locale = "{{ config('app.fallback_locale') }}";
</script>
and added this to app.js:
import Vue from 'vue';
import Lang from 'lang.js';
const default_locale = window.default_language;
const fallback_locale = window.fallback_locale;
const messages = window.messages;
Vue.prototype.trans = new Lang( { messages, locale: default_locale, fallback: fallback_locale } );
According to the documentation, you should now be able to use it in any vue component, but when I try to use it like this:
<tr>
<th>{{ trans.get('dashboard.headers.name') }}</th>
</tr>
I get this error:
[Vue warn]: Error in render: "TypeError: Cannot read property 'get' of null"
Any idea where I'm going wrong?
UPDATE:
figured out the first issue. You have to add this line:
Vue.prototype.trans = new Lang( { messages, locale: default_locale, fallback: fallback_locale } );
before creating the vue instance:
const app = new Vue({
el: '#app'
});
I was doing it afterwards.
I am however now facing a next issue, I expected that this would now give me a proper result:
{{ trans.get('dashboard.headers.name') }}
but it just returns dashboard.headers.name', console.log(this.trans.has('dashboard.headers.name'))also returns false.
if I look at the result from the ajax call, it seems that the key is there alright:
But it seems lang.js requires a slightly different format:
{
'en.greetings': {
'hi': 'Hi',
'hello': 'Hello'
},
'it.greetings': {
'hi': 'Salve'
}
}
});
so the kg-bot/laravel-localization-to-vue package is just not exporting the data in a way that lang.js understands. It turned out I had to change it to use the toFlat method instead of the toArray method to get the translations in the right format:
However, the translations are still not working. When I replace
window.messages = axios.get('http://localhost:8083/js/localization.js')
by just placing the response of the ajax call in messages, it is working, so apparently it doen't like the promise that is assigned to it now.


window.Vue = require('vue');instead ofimport Vue from 'vue';and it works for me.this.trans.get('dashboard.headers.name').