You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue template中复用相同模板片段以避免重复代码

完全可以,Vue template场景下有多种和JSX封装渲染函数等价的模板复用方案,无需重复编写代码。

方案1:单文件内复用(Vue 3.3+ 支持,无需抽离组件)

这是最贴近JSX封装函数用法的方案,适合仅在当前组件内复用的片段,不需要额外新建组件文件。

  1. 在<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>
  1. 在template中直接调用,完全匹配你示例的使用方式:
<template>
  <ElementToUse />
  <!-- 传参用法 <ElementToUse title="自定义标题" description="自定义描述" /> -->

  <tooltip>
    <template #content>
      <ElementToUse />
    </template>
    <div>
      <img src="/img.png" />
      <ElementToUse />
    </div>
  </tooltip>
</template>

方案2:抽离为独立公共组件(全版本兼容,适用范围最广)

如果片段需要在多个组件中复用,直接抽为独立的小组件即可,Vue2、Vue3所有版本都支持。

  1. 新建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. 在需要使用的组件中引入后直接调用即可,用法和方案1完全一致。

补充说明

  • 如果使用Vue2或者低于3.3版本的Vue3,直接用方案2即可,实现成本极低。
  • 如果复用的片段需要支持自定义内容,可在组件中预留插槽,使用时传入自定义插槽内容即可,灵活性更高。

内容的提问来源于stack exchange,提问作者Djaangoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:24:07