Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register local Vue.js component dynamically

We know it possible to register global Vue.js (version 1) components dynamically like this:

Vue.component('my-component', MyComponent)

Is there a way to do the same for local components, i.e. those available/visible only to a specific component?

The idea is that I want to be able to pass components to be locally registered like this:

<outer-component
  :local-component-to-be-registered-dymanically="Foo"
>

So that in the outer-component I could then do:

created() {
    this.someMethodINeedToRegisterLocalComponent('cool-component', this.localComponentToBeRegisteredDynamically);
},
like image 973
Greendrake Avatar asked Nov 16 '16 01:11

Greendrake


People also ask

How do I dynamically load components in Vue?

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.

How do I register a component in Vuejs?

When we want to globally register a component in Vue, we need to do it in this file. All you have to do is import your component, as you usually would, and then register it using app. component . import { createApp } from 'vue' import App from './App.


1 Answers

This is how I ended up importing and registering components dynamically to a component locally:

created() {
  const requireComponent = require.context(
    // The relative path of the components folder
    "PATH/TO/COMPONENTS_FOLDER",
    // Whether or not to look in subfolders
    false,
    // The regular expression used to match base component filenames
    /[A-Z]\w+\.(vue|js)$/
  );

  requireComponent.keys().forEach(fileName => {
    const componentConfig = requireComponent(fileName);
    console.log(componentConfig.default);
    // Gets the file name regardless of folder depth
    const componentName = fileName
      .split("/")
      .pop()
      .split(".")[0];
    // register the component locally
    this.$options.components[componentName] = componentConfig.default;
  });
}

Please notice that the components have to be registered before the component is mounted, the created life-cycle hook can be perfect for that.

See also the docs for Automatic Global Registration of Base Components.

like image 112
Shaya Ulman Avatar answered Oct 20 '22 06:10

Shaya Ulman