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?
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM