简体   繁体   中英

How to load a vue component in js file

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?

I'd rather do it this way:


import FalseDiscoverComponent from './components/FalseDiscoverComponent.vue'
import TrueDiscoverComponent from './components/TrueDiscoverComponent.vue'


Vue.component({
    'discover-component',

    components: {
        FalseDiscoverComponent, TrueDiscoverComponent 
    }

    template: `
        <div>
            <true-discover-component v-if="contidion" />
            <false-discover-component v-else />
        </div>
    `
})

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://v2.vuejs.org/v2/guide/components-dynamic-async.html#Async-Components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM