How to dynamically import components

How to dynamically import components


foreword

When a page needs to import many components, and each component is independent, you can consider using dynamic components, so you don’t have to fill in so many times.


1. html part

First, use the compoent tag in the html part, and use is to bind the value you give to the dynamic component, which is a string type

<component :is="component.name"></component>

2. js part

First of all, you need to understand that no matter how dynamic a dynamic component is, it needs a source, so you also need to import and register the component that needs to be referenced. Suppose I have a.vue component, and I want to import it in component b, so I need to import it in component b First import import and register, and then write a method to get the component where you need to get the component and create it

import a from './a.vue'; // 具体看你需要导入的组件
export default {
    
    
	component: {
    
    a},
	data() {
    
    
		return {
    
    
			component: {
    
    },
		}
	},
	// 具体位置看你需要在哪里导入
	created() {
    
    
		var name = 'a'; // 这个a是我想导入的组件,所以赋值a,若是从后端获取,则修改为后端获取的值即可
		var myComponent =() => import('./components/' + name + '.vue');
		this.component={
    
    
			name:name,
			component:myComponent
		}
	}
}

So far and can be completed

There is also a require method, which will be added next time


important point

No matter how dynamic the component is, there will always be a source, so the steps of import and component must be written, otherwise the component cannot find the source

Guess you like

Origin blog.csdn.net/qq_51741730/article/details/126331753