Ad

How To Load A Vue Component In Js File

- 1 answer

I would obtain the following behavior: if in my database a certain condition is present, I would to load a specific vue.component instead of another. In other word, I have a file called discover.js that inside it has the following code:

Vue.component(
    'discover-component',
    require('./components/DiscoverComponent.vue').default
);

I would call the DiscoverComponent.vue only if the user (so in the db is set a specific boolean as true) and otherwise I would call another component. This is an example in pseudocode:

If flag is true:

    Vue.component(
        'discover-component',
        require('./components/TrueDiscoverComponent.vue').default
    );

Else:

    Vue.component(
        'discover-component',
        require('./components/FalseDiscoverComponent.vue').default
    );

Should I use AJAX call in this file .js to load the value of the flag? Is it legit? Or Is it a bad practice to call data inside a js file instead of a controller?

Ad

Answer

In this case, I think you can use the async components. Something like this:

Vue.component('discover-component', async () => {
  const response = await fetch('/get-user'); 
  const user = await response.json();
  if (user.flag) {
    return import('./components/TrueDiscoverComponent.vue');
  }
  return import('./components/FalseDiscoverComponent.vue');
})

The link for async components documentation page: https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components

Ad
source: stackoverflow.com
Ad