全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-20 5 分钟 ✍️ juanwangdev

组件模板

模板是组件的视图部分,定义了渲染结构。

单文件组件模板

vue
<template>
  <div class="user-card">
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: { name: '张三', email: 'test@example.com' }
    }
  }
}
</script>

内联模板

JavaScript
export default {
  template: `
    <div>
      <h2>{{ title }}</h2>
      <p>{{ content }}</p>
    </div>
  `,
  data() {
    return {
      title: '标题',
      content: '内容'
    }
  }
}

模板约束

每个组件模板必须有且仅有一个根元素(Vue 3 支持多根,但推荐单根):

vue
<!-- 推荐 -->
<template>
  <div>
    <h1>标题</h1>
    <p>内容</p>
  </div>
</template>

动态模板

vue
<template>
  <component :is="currentComponent"></component>
</template>

使用 <component> 标签动态切换组件。

要点总结

  • 单文件组件将模板、逻辑、样式放在一个文件中
  • 内联模板适合简单组件
  • 推荐单根元素结构
  • <component :is="..."> 支持动态组件切换
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 组件注册
下一篇 → 组件数据与方法
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码