vue中的插槽相信使用过vue的小伙伴或多或少的都用过,但是你是否了解它的用法呢?本篇文章就为大家带来vue中插槽slot基本使用和具名插槽,希望对大家有所帮助!

⭐⭐
初识插槽:
div、span等等这些元素;【相关推荐:vuejs视频教程】换句话说就是,我们要是想在一个组件标签中添加新的内容,那么我们就需要在该组件内声明一个插槽,不然,添加的新内容不会被渲染
⭐⭐
使用插槽:
立即学习“前端免费学习笔记(深入)”;
slot元素作为插槽slot标签中设置一个默认内容使用插槽案例:
父组件
App.vue
<template>
<div class="app">
<!-- 内容是button -->
<show-message title="哈哈哈">
<button>我是按钮元素</button>
</show-message>
<!-- 内容是超链接 -->
<show-message>
<a href="#">百度一下</a>
</show-message>
<!-- 没有值传递 -->
<show-message></show-message>
</div>
</template>子组件showMessage.vue
<template>
<h2>{{title}}</h2>
<div class="content">
<slot>
<p>我是默认值</p>
</slot>
</div>
</template>
showMessage里面,我们给它一个插槽,App.vue, 我们给showMessage三次复用,一次为按钮,一次为a标签,一次什么也不加
一个为按钮,一个为a链接,一个为插槽默认的p标签我们可以看出来
⭐⭐
希望达到的效果是插槽对应内容的显示,这个时候我们就可以使用具名插槽:
slot 元素有一个特殊的 attribute:name; name 的slot,会带有隐含的名字 default;template标签, 并在template中使用#
父组件App.vue
<template>
<nav-bar>
<template v-slot:left>
<button>返回</button>
</template>
<template v-slot:center>
<span>内容</span>
</template>
<template v-slot:right>
<a href="#">登录</a>
</template>
</nav-bar>
</template>子组件NavBar.vue
(颜色啥的css里面自己可以调,这里就不放了)
<template>
<div class="nav-bar">
<div class="left">
<slot name="left">left</slot>
</div>
<div class="center">
<slot name="center">center</slot>
</div>
<div class="right">
<slot name="right">right</slot>
</div>
</div>
</template>效果图:
达到的效果是插槽对应的显示
所以这就是具名插槽的作用
⭐⭐
动态插槽名
通过 v-slot:[dynamicSlotName]方式动态绑定一个名称;
Ps:还有作用域插槽,我目前还不是很理解,先不写了~
以上就是浅析Vue中插槽Slot的作用和具名插槽的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号