Vue.js 动态组件与组件的复用
在 Vue 开发中,你经常会遇到这样一种需求:同一个位置需要渲染不同的组件,或者想要根据条件切换组件,而不是写很多 v-if
来控制。这时候你就可以使用动态组件功能。此外,组件的复用也是开 发中提升效率和可维护性的重要手段。本文将带你了解 动态组件
和 组件复用
的基本用法与最佳实践。
什么是动态组件?
在 Vue 中,你可以通过 <component>
标签来渲染一个“动态”的组件。只需要将组件名称或组件对象赋值给 :is
属性,Vue 就会自动渲染对应的组件。
你可能会在以下场景中用到动态组件:
- 选项卡组件(Tabs):不同的 tab 显示不同的组件内容。
- 多步骤表单:根据当前步骤渲染不同的表单页面。
- 内容编辑器插件:可切换不同类型的输入组件。
示例:根据按钮切换不同组件
<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import { ref } from 'vue'
const currentComponent = ref('Foo')
</script>
<template>
<button @click="currentComponent = 'Foo'">显示 Foo</button>
<button @click="currentComponent = 'Bar'">显示 Bar</button>
<component :is="currentComponent" />
</template>
在上面的示例中,<component :is="currentComponent" />
会根据变量 currentComponent
的值动态渲染 <Foo />
或 <Bar />
组件。
你也可以传入组件对象而非字符串:
<component :is="currentComponentObject" />