1

I want create global method to translate message using Laravel-JS-Localization

But when i call the method using vue mustache got an error like this:

Property or method "trans" is not defined on the instance but referenced during render.
Make sure that this property is reactive.

Here my laravel app.js code:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('dashboard', require('./components/Dashboard').default);

const app = new Vue({
  el: '#vue',
  methods: {
    trans: function (key) {
      return Lang.get(key);
    },
  },
});

Dashboard.vue code :

<template>
 <p>{{ trans('common.welcome') }}</p>
</template>

<script>
 data () {
  return {
   name: '',
  }
 },
</script>

dashboard.blade.php code :

..........

    <div class="col-9" id="vue">
     <dashboard></dashboard>
    </div> <!--c end col-8 -->

..........

1 Answer 1

2

I would probably go with creating a Plugin. For example

Vue.use({
  install (Vue) {
    Vue.prototype.$trans = Lang.get
  }
})

Adding this to your app.js code before creating any components or new Vue({...}) will mean all your components will have access to the $trans method.


Alternatively, you can create a Global Mixin but these aren't strongly recommended.

Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components

Vue.mixin({
  methods: {
    trans (key) {
      return Lang.get(key)
    }
  }
})
Sign up to request clarification or add additional context in comments.

2 Comments

@PanjiSetyaNurPrawira I've updated my answer. I suggest using a plugin over a global mixin but I've provided details of both
Thank u for the explanation i will try it ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.