最近参与了一个Vue.js项目,项目中需要能够以编程方式创建组件。通过编程,意思是使用JavaScript创建和插入组件,而无需在模板中编写任何内容。本文接下来将介绍在模板中使用组件的各个方面,例如实例化,传递Props,插槽,挂载,转换为JavaScript代码。
通常,会推荐使用"单个文件组件"。比如一个Button组件,如下所示:
<template>
<button :class="type"><slot /></button>
</template>
<script>
export default {
name: 'Button',
props: [ 'type' ],
}
</script>
要在另一个组件中使用它,您要做的就是导入Button组件并将其标签插入模板中:
<template>
<Button type="primary">Click me!</Button>
</template>
<script>
import Button from 'Button.vue'
export default {
name: 'App',
components: { Button }
}
</script>
就项目需求而言,我不知道在模板中插入哪个组件以及在哪里插入。因此,我需要一种能在运行时为任何组件动态创建组件实例并将其插入DOM的方法。
创建实例
最初想法是使用new。但是,它将导出一个简单的对象,而不是类(构造函数)。如果我这样做:
import Button from 'Button.vue'
const instance = new Button()
上面的代码将失败。Button是一个对象,不是构造函数,不能new。我们需要的是一个Class,构造函数。我将组件对象传递给Vue.extend以创建Vue构造函数的子类。现在,我们可以使用new关键字从中创建一个实例:
import Button from 'Button.vue'
import Vue from 'vue'
const ComponentClass = Vue.extend(Button)
const instance = new ComponentClass()
完美!现在我们需要将其插入DOM中。
完整内容,请访问:宅码,以编程方式创建Vue.js组件实例