Currently I am loading all of my Vue components with require.context
, this searches my components
directory with a regex for .vue
files. This works fine but I would like to load async components as well with dynamic imports.
Currently when I use require.context
all files get loaded so even If I want to use a dynamic import my file is already loaded and nothing happens.
I need a way to exclude certain files from my require.context
call. I cannot dynamically create a regex because this does not work with require.context
.
// How I currently load my Vue components.
const components = require.context('@/components', true, /[A-Z]\w+\.vue$/);
components.keys().forEach((filePath) => {
const component = components(filePath);
const componentName = path.basename(filePath, '.vue');
// Dynamically register the component.
Vue.component(componentName, component);
});
// My component that I would like to load dynamically.
Vue.component('search-dropdown', () => import('./search/SearchDropdown'));
It seems the only way to do this is either manually declare all my components, which is a big hassle.
Or to create a static regex that skips files that have Async
in their name. Which forces me to adopt a certain naming convention for components that are async. Also not ideal.
Would there be a better way to go about doing this?
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
To make the component dynamic, we can bind it to a set property with the v-bind directive. Your component is now bound with the component property in the data. If you switch the component to Test2 , it will automatically mount the Test 2 component. Test it out on your browser.
STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.
vue file. Lazy loading refers to an approach by which all the scripts are not loaded on the DOM as the application starts. Instead, they're only loaded when requested, which makes the JavaScript bundle size very small at initial load. Vue.
const requireContext = require.context('./components', false, /.*\.vue$/)
const dynamicComponents = requireContext.keys()
.map(file =>
[file.replace(/(^.\/)|(\.vue$)/g, ''), requireContext(file)]
)
.reduce((components, [name, component]) => {
components[name] = component.default || component
return components
}, {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With