How vue parent components dynamically register child components

the components of vue are usually import, registered in components, and then can be used in the parent component, but now the component of the project is the component name obtained from the background, and then if else determines whether there is an import component, and finally generates it. Fortunately, there were only 4 components in 3Jing in the early stage, but then there were more and more. If else is getting longer and longer, and then I wonder if there is a way to register components dynamically. I read it on the official website and looked around on the Internet. Someone once wrote this

.
/**
*@desc */
registerComponent(templateName){
 Vue.component(templateName,    require("./../dashComponent/"+templateName+".vue"));
},

Registration scheme

this.registerComponent(this.layout[index].component);



dom

clipboard.png

clipboard.png

clipboard.png

this should not be registered successfully, has any classmate encountered this kind of situation before?

Mar.02,2021

Vue.component (templateName,require (. / heNan/$ {templateName} .vue ) .default); it can be used this way, but import's


is encouraged.

the code upstairs is incorrect. Normally,
name: refers to the name of the file, such as test.vue, so name means to write test

.
<template>
<div ref="xxx"></div>
</template>
import Vue from "vue";

registerComponent(name) {
  return import("@/components/" + name);
 };
 
  this.registerComponent(name).then(component => {
    const cpt = Vue.extend(component.default);
    new cpt({
      el: this.$refs.xxx
    });
  });

does not encounter this situation. If it is to optimize component loading performance, consider loading on demand


register function

/**
*@desc 
*@return {Promise}
*/
registerComponent(templateName){
  return import(`./../dashComponent/${templateName}.vue`).then((component) => {
    return Vue.extend(component)
  })
}

component dynamic mount

this.registerComponent(templateName).then((Component) => {
    new Component({el: yourNeedEl})
})

or this

registerComponent(templateName){
  return import(`./../dashComponent/${templateName}.vue`).then((component) => {
    return Vue.component(templateName, component)
  })
}

https://www.cnblogs.com/stone.

Menu