Vue implements dynamic insertion of custom components and value passing of component props based on the extend method, "js-dynamic-components".

insert image description here

1. Application scenarios

In many cases, the development of vue projects requires dynamic control of the custom components we develop ourselves, so as to achieve rendering according to the components we want, and at the same time, we can dynamically manage the rendering and display of custom components on the front end.
So how?

2. Realization

1. Principle

Vue.extend(): Create a "subclass" using the base Vue constructor. The argument is an object containing options for the component.
Simply put, we can use the Vue.extend() method to create a component out of thin air in the template template, the effect is similar to adding and generating DOM elements in JQuery or es6 (js).

2. Realize

var tipComponent = Vue.extend({
    
    
    render: (h) =>
      h(Assembly, {
    
    
        props: {
    
    
          Transfer_data:Tvalue
        }, //组件传值
      }),
  }); //生成组件的dom
  const component = new tipComponent().$mount();
  var DomContent = component.$el; //将vue结构转化成dom
  document.getElementById(Id).appendChild(DomContent);

3. Package use

1. Install this project

npm i js-dynamic-components

2. Use this project

// 在您的vue组件当中导入npm包
import {
    
    Dynamically_insert_components} from 'js-dynamic-components'
// 使用本项目 示例如下 直接调用该方法
Dynamically_insert_components(Assembly,Tvalue,Id)

3. Examples

// 例如 自注册,或者全局注册的自定义组件
import com2 from './Home'
export default {
    
    
    components: {
    
    
        com2
    },
    data() {
    
    
        return {
    
    
            data:'数据传值测试1'
        };
    },
    mounted() {
    
    
        this.ss()
    },
    methods: {
    
    
        ss(){
    
    
            Dynamically_insert_components(com1,this.data,"a1")
        }
    },
};

4. Parameter description

parameter Parameter Description
Notice Before using js-dynamic-components, you need to perform an npm i initialization operation on your own development project (because the Vue-based extend method is implemented, you need to restore and install Vue)
Assembly Customize the component name, just import it
Tvalue props pass value, string, array, object can be passed, subcomponent props pass value parameter Transfer_data
Id The id of the DOM that needs to be added to the vue custom component, the string is passed in, "id"

This article is original, and it is not easy to be original. If you need to reprint, please contact the author for authorization.

Guess you like

Origin blog.csdn.net/qq_36034945/article/details/129966710