<template>标签的作用是什么?<slot>标签的作用是什么?

<template><slot> 都是 Vue.js 框架中用于模板编程的标签,但它们在功能和应用场景上有所不同。

1. <template> 标签的作用

<template> 标签在 Vue.js 中用作一种声明性的方式来定义模板的片段。但它本身不会被渲染到最终的 DOM 中。<template> 的主要用途有:

  1. 条件渲染 :使用 v-ifv-else-ifv-else 来控制模板片段的渲染。
javascript 复制代码
<template>  
  <div>  
    <p v-if="showMessage">Hello, Vue!</p>  
    <p v-else>Goodbye, Vue!</p>  
  </div>  
</template>
  1. 列表渲染 :使用 v-for 指令来渲染列表。
javascript 复制代码
<template>  
  <div>  
    <ul>  
      <li v-for="(item, index) in items" :key="index">{{ item }}</li>  
    </ul>  
  </div>  
</template>
  1. 包装多个元素 :在 Vue 的模板中,一个组件通常只能有一个根元素。但有时你可能需要包装多个元素。这时,你可以使用 <template> 作为包裹元素,但请注意,<template> 本身不会被渲染到最终的 DOM 中。
javascript 复制代码
<template>  
  <template v-if="showMultipleElements">  
    <p>First paragraph.</p>  
    <p>Second paragraph.</p>  
  </template>  
</template>

2. <slot> 标签的作用

<slot> 标签在 Vue.js 中用于内容分发。在子组件中,你可以使用 <slot> 标签作为内容的插槽,然后在父组件中使用该子组件时,向这个插槽插入内容。

  • 默认插槽 :当子组件中只有一个 <slot> 时,它就是默认插槽。

子组件:

javascript 复制代码
<template>  
  <div>  
    <h2>Welcome to My Component</h2>  
    <slot></slot>  
  </div>  
</template>

父组件:

javascript 复制代码
<template>  
  <my-component>  
    <p>This is some content inserted into the slot.</p>  
  </my-component>  
</template>
  • 具名插槽 :当子组件中有多个 <slot> 时,可以给它们命名以区分。

子组件:

javascript 复制代码
<template>  
  <div>  
    <header>  
      <slot name="header"></slot>  
    </header>  
    <main>  
      <slot></slot>  
    </main>  
    <footer>  
      <slot name="footer"></slot>  
    </footer>  
  </div>  
</template>

父组件:

javascript 复制代码
<template>  
  <my-component>  
    <template v-slot:header>  
      <h1>This is the header</h1>  
    </template>  
    <p>This is some default content.</p>  
    <template v-slot:footer>  
      <p>This is the footer</p>  
    </template>  
  </my-component>  
</template>

这样,你就可以在父组件中向子组件的不同插槽插入不同的内容了。

相关推荐
摇滚侠2 小时前
npm 设置了阿里云镜像,然后全局安装了 pnpm,pnpm 还需要设置阿里云镜像吗
前端·阿里云·npm
程序员清洒8 小时前
Flutter for OpenHarmony:GridView — 网格布局实现
android·前端·学习·flutter·华为
VX:Fegn08958 小时前
计算机毕业设计|基于ssm + vue超市管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·课程设计
0思必得08 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
LawrenceLan8 小时前
Flutter 零基础入门(二十六):StatefulWidget 与状态更新 setState
开发语言·前端·flutter·dart
秋秋小事8 小时前
TypeScript 模版字面量与类型操作
前端·typescript
2401_892000529 小时前
Flutter for OpenHarmony 猫咪管家App实战 - 添加提醒实现
前端·javascript·flutter
Yolanda949 小时前
【项目经验】vue h5移动端禁止缩放
前端·javascript·vue.js
VX:Fegn089510 小时前
计算机毕业设计|基于springboot + vue酒店管理系统(源码+数据库+文档)
vue.js·spring boot·课程设计
广州华水科技10 小时前
单北斗GNSS形变监测一体机在基础设施安全中的应用与技术优势
前端