Rejoanul Alam
Rejoanul Alam

Reputation: 5398

vueJS mixin trigger multiple times in laravel 5.7

I am new in Vue jS [version 2]. There are 3 component in my page. I want to use a axios get data available in all pages. I have done as follows in my app.js

const router = new VueRouter({mode: 'history', routes });
Vue.mixin({
data: function () {
        return {
          pocketLanguages: [],

        }
    },
mounted() {
       var app = this;
       axios.get("/get-lang")
            .then(function (response) {
                app.pocketLanguages = response.data.pocketLanguages;
        })
    }
})

const app = new Vue({ 
    router,
}).$mount('#app');

and using this pocketLanguages in a component like

{{ pocketLanguages.login_info }} this. Its working fine but My Issue is axios.get('') triggering 4 times when page load [in console]

enter image description here

Now how can I trigger this only once or anything alternative suggestion will be appreciated to do this if explain with example [As I am new in Vue]

Upvotes: 1

Views: 1614

Answers (2)

Husam Elbashir
Husam Elbashir

Reputation: 7177

You are using a global mixin, which means that every component in your app is going to make that axios get call when it's mounted. Since your page has several components in it, no wonder the call is being made several times. What you need to do here is either:

  1. Create a normal mixin and only use it in the master/container/page component in every route that actually needs to fetch the data by providing the option mixins: [yourMixinsName]. That component can then share the data with the other components in the page.

  2. If your data is common between pages then it's better to use a global store such as Vuex to simplify state management.

On a side note: It is usually better to handle your data initialization in the created hook. Handling it in the mounted hook can lead to some pitfalls that include repeated calls, among other things, due to parent/child lifecycle hooks execution order. Please refer to this article for more information on the subject.

Upvotes: 5

Rejoanul Alam
Rejoanul Alam

Reputation: 5398

Finally problem solved

In resources/js/components/LoginComponent.vue file

<script>
import translator from '../translation';

export default {
    mixins:[translator],
    beforeCreate: function() {
        document.body.className = 'login-list-body';
    },
.....

mounted() {
        this.langTrans();
    }

and my translation.js file at /resources/js

export default {
 data: function() {
  return {
    pocketLanguages: []
  };
},
methods: {
langTrans: function() {
    var self = this;
    axios.get('/get-lang')
              .then(function (response) {
                  self.pocketLanguages = response.data.pocketLanguages;
              }); 
   }

  }
};

Upvotes: -1

Related Questions