在 Vue 中,定义组件模板(template)有多种方式,适用于不同的开发场景和项目需求。以下是主要的几种方法,涵盖 Vue 2 和 Vue 3 的实践。
一、1. 单文件组件(SFC)中的 <template>
标签(最常用)
这是现代 Vue 项目的标准做法,将模板写在 .vue
文件的 <template>
标签中。
<!-- MyComponent.vue -->
<template>
<div class="my-component">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
content: 'This is a template.'
}
}
}
</script>
✅ 优点:
- 语法高亮、格式化支持好。
- 与
<script>
和<style>
同文件,结构清晰。- 支持编译时优化(如静态提升)。
二、2. 在 <script>
中使用 template
字符串
将模板作为字符串直接写在组件的 template
选项中。
// MyComponent.js
export default {
template: `
<div class="my-component">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
`,
data() {
return {
title: 'Hello',
content: 'Inline template.'
}
}
}
⚠️ 注意:
- 需要使用 完整版 Vue(包含编译器),不能使用
vue.runtime.esm.js
。- 不支持语法高亮,长模板不易维护。
三、3. 使用 render
函数(编程式模板)
通过 JavaScript 函数返回虚拟 DOM(VNode),完全编程化地定义模板。
Vue 2 写法:
export default {
data() {
return {
title: 'Render Function'
}
},
render(h) {
return h('div', { class: 'my-component' }, [
h('h1', this.title),
h('p', 'This is created with render function.')
])
}
}
Vue 3 写法(使用 h
函数):
import { h } from 'vue'
export default {
setup() {
return () => h('div', { class: 'my-component' }, [
h('h1', 'Hello'),
h('p', 'This is Vue 3 render function.')
])
}
}
✅ 优点:
- 灵活性极高,可动态生成结构。
- 适合复杂逻辑或动态 UI。
- 性能好(直接操作 VNode)。
❌ 缺点:
- 模板逻辑与 JavaScript 混合,可读性较差。
四、4. 使用 JSX / TSX
在支持 JSX 的项目中(如 Vue 3 + Vite/Babel),可以直接使用 JSX 语法。
// MyComponent.jsx
import { ref } from 'vue'
export default {
setup() {
const title = ref('JSX Template')
return () => (
<div class="my-component">
<h1>{title.value}</h1>
<p>This is JSX.</p>
</div>
)
}
}
✅ 优点:
- JavaScript 与模板无缝结合。
- 适合熟悉 React 的开发者。
- 支持 TypeScript 类型检查。
⚠️ 需要配置:Babel 或 Vite 支持
@vitejs/plugin-vue-jsx
。
五、5. 使用 #id
引用 DOM 元素作为模板
从页面中某个 DOM 元素的 innerHTML
作为模板(主要用于非构建环境或渐进式增强)。
<!-- index.html -->
<div id="app"></div>
<script type="text/x-template" id="my-template">
<div class="my-component">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</script>
new Vue({
el: '#app',
template: '#my-template',
data: {
title: 'DOM Template',
content: 'Loaded from DOM.'
}
})
⚠️ 限制:
- 需要完整版 Vue(含编译器)。
- 不支持在构建工具(如 Webpack/Vite)中使用。
- 已逐渐被淘汰,仅用于特殊场景。
六、6. 使用 <script setup>
+ 模板(Vue 3 推荐)
在 <script setup>
中定义逻辑,模板仍写在 <template>
中,是目前最主流的方式。
<script setup>
import { ref } from 'vue'
const title = ref('Composition API')
</script>
<template>
<div class="my-component">
<h1>{{ title }}</h1>
<p>Using <script setup></p>
</div>
</template>
七、总结:各种模板定义方式对比
方法 | 适用场景 | 是否推荐 | 备注 |
---|---|---|---|
<template> 标签 | 所有现代项目 | ✅ 强烈推荐 | 最清晰、生态好 |
template 字符串 | 简单组件、动态模板 | ⚠️ 一般 | 需完整版 Vue |
render 函数 | 高级组件、动态 UI | ✅ 推荐(特定场景) | 灵活性高 |
JSX / TSX | JSX 爱好者、TypeScript 项目 | ✅ 推荐 | 需配置 |
DOM 元素模板 | 旧项目、非构建环境 | ❌ 不推荐 | 已过时 |
✅ 最佳实践:
- 大多数项目:使用
<template>
+<script setup>
。- 需要高度动态 UI:使用
render
函数。- 熟悉 JSX:使用
.jsx
/.tsx
文件。
掌握这些方式,可以根据项目需求灵活选择最合适的模板定义方法。
THE END