2
votes

I made a "OffersPlugin" that during "install" function get some data from server. And that data is needed in first component loaded in vue. But http request can't finish before vue component is loaded and I don't have any data to use.

How can I tell vue to hold init vue before plugin is ready?

Thank you.


import Vue from 'vue';

import VueCookie from 'vue-cookie';
import App from './ExampleComponent';

import OffersPlugin from '../plugins/OffersPlugin';


Vue.use(VueCookie);
Vue.use(OffersPlugin);

if(document.getElementById("vue-promotion-edit-section")) {
    new Vue({

        render: h => h(App)
    }).$mount('#vue-promotion-edit-section');

In install method I have axios GET request. In that request I load from server list of offers. When request is success then I make plugin variable associated array:

const offerList = [];

As a prototype I use method getOfferId.

function(name) 
{
return offersList[name] || 'No offer'
}

2
Would you like to show how the OffersPlugin code looks like? - Jefry Dewangga
I can't show exactly it right now (I'm on other pc). I edited my question added plugin concept. - Klick
Why don't use conditional statement v-if to check if array is empty or not to render what you need? - Daniyal Lukmanov
My base question: is it possible to mount "vue" when plugin finish http request and data in plugin is ready? I could use v-if or something else like use store. But in this case I need functionality that I described. - Klick

2 Answers

5
votes

HTTP request is asynchronous by nature. Vue initialisation is synchronous by nature. You cannot make a synchronous result out of an asynchronous operation in Javascript.

Workaround :

OffersPluginFactory.js:

const pluginFactory = function() {
  let promise = axios.get()
    .then(...process data...)
    // return plugin object with data inside
    .then(data => ({
      install(Vue, options) {
        ...use data here...
      }
    }));
  return promise; // when resolved this promise returns plugin object
}

export default pluginFactory;

main.vue:

import OffersPluginFactory from '../plugins/OffersPluginFactory';

OffersPluginFactory().then( function(plugin) {
  Vue.use(plugin)

  new Vue({
    render: h => h(App)
  }).$mount('#vue-promotion-edit-section');
} 
);