如何在Vue template中复用相同模板片段以避免重复代码
完全可以,Vue template场景下有多种和JSX封装渲染函数等价的模板复用方案,无需重复编写代码。
方案1:单文件内复用(Vue 3.3+ 支持,无需抽离组件)
这是最贴近JSX封装函数用法的方案,适合仅在当前组件内复用的片段,不需要额外新建组件文件。
- 在
<script setup>中定义模板片段:
<script setup> import { ref, defineTemplate } from 'vue' // 直接使用当前组件的响应式变量,无需额外传参 const title = ref('默认标题') const description = ref('默认描述内容') const ElementToUse = defineTemplate(() => ` <div class="element-to-use"> <h1>{{ title }}</h1> <p>{{ description }}</p> </div> `) // 如果需要支持传入不同参数,也可以定义props // const ElementToUse = defineTemplate<{ // title: string // description: string // }>((props) => ` // <div class="element-to-use"> // <h1>{{ props.title }}</h1> // <p>{{ props.description }}</p> // </div> // `) </script>
- 在template中直接调用,完全匹配你示例的使用方式:
<template> <ElementToUse /> <!-- 传参用法 <ElementToUse title="自定义标题" description="自定义描述" /> --> <tooltip> <template #content> <ElementToUse /> </template> <div> <img src="/img.png" /> <ElementToUse /> </div> </tooltip> </template>
方案2:抽离为独立公共组件(全版本兼容,适用范围最广)
如果片段需要在多个组件中复用,直接抽为独立的小组件即可,Vue2、Vue3所有版本都支持。
- 新建
ElementToUse.vue组件文件:
<template> <div class="element-to-use"> <h1>{{ title }}</h1> <p>{{ description }}</p> </div> </template> <script setup> // 定义可传入的参数 defineProps({ title: { type: String, default: '默认标题' }, description: { type: String, default: '默认描述' } }) </script>
- 在需要使用的组件中引入后直接调用即可,用法和方案1完全一致。
补充说明
- 如果使用Vue2或者低于3.3版本的Vue3,直接用方案2即可,实现成本极低。
- 如果复用的片段需要支持自定义内容,可在组件中预留插槽,使用时传入自定义插槽内容即可,灵活性更高。
内容的提问来源于stack exchange,提问作者Djaangoo
相关产品推荐
相关产品推荐

