Can you dinamically fetch components from a folder and list all of them in Vue 2?
Yes, you can dynamically fetch components from a folder and list them in Vue 2. Here's one approach:
1. Create a new Vue component (let's call it "DynamicComponents") that will serve as the container for your dynamically loaded components.
2. Use the require.context( ) method to get a context for the directory containing your components. For example, if your components are in a directory called "components", you can get the context like this:
This will give you a context that you can use to dynamically load all components that match a certain naming convention (in this case, any component whose filename starts with "Base" and ends in ".vue" or ".js").
3. Use the keys( ) method on the context to get an array of all the filenames that match the naming convention. For example:
4. Loop through the array of filenames and dynamically import each component using the requireComponent( ) method. For example:
This will dynamically import each component and register it globally with Vue, using the component name derived from the filename.
5. Use the <component> element in your "DynamicComponents" component to render each dynamically loaded component. For example:
This will render a <component> element for each dynamically loaded component, using the component name as the value of the is attribute.
Note: Make sure to run this code before you create your root Vue instance. This will ensure that all dynamically loaded components are registered globally before your app is initialized.
No comments