<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>

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

相关推荐
LilyCoder3 分钟前
HTML5二十四节气网站源码
前端·javascript·html·html5
nyf_unknown7 分钟前
(vue)将文件夹打成tar包, Git Bash(推荐)具体使用
vue.js·git·bash
Bruce_Liuxiaowei16 分钟前
跨站脚本攻击(XSS)高级绕过技术与防御方案
前端·网络安全·xss
EF@蛐蛐堂31 分钟前
【vue3】v-model 的 “新玩法“
前端·javascript·vue.js
两个月菜鸟40 分钟前
vue+微信小程序 五角星
前端·vue.js·微信小程序
GISer_Jing2 小时前
React手撕组件和Hooks总结
前端·react.js·前端框架
Warren986 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
mCell6 小时前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
amy_jork8 小时前
npm删除包
开发语言·javascript·ecmascript
帧栈10 小时前
开发避坑指南(27):Vue3中高效安全修改列表元素属性的方法
前端·vue.js