全部学科
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="..."> 支持动态组件切换

📝 发现内容有误?点击此处直接编辑

← 上一篇 组件样式作用域
下一篇 → 组件注册
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库