Vue3开发极简入门(18):插槽Slot

Vue3开发极简入门(18):插槽Slot大家一看代码就知道插槽用在什么地方了 简单说就是父组件在引用子组件时 里面填写的内容 可以填充到子组件的 slot slot 里面 默认插槽 src components MyBtn

大家好,欢迎来到IT知识分享网。

大家一看代码就知道插槽用在什么地方了。

简单说就是父组件在引用子组件时,里面填写的内容,可以填充到子组件的<slot></slot>里面。

默认插槽

src/components/MyBtn.vue:

<template> <button class="solid-button red-button"> <slot>默认内容</slot> </button> </template> <script lang='ts' setup name='MyBtn'> </script> <style scoped> .solid-button { display: inline-block; padding: 10px 20px; font-size: 16px; color: white; text-align: center; text-decoration: none; border-radius: 5px; border: none; cursor: pointer; } .red-button { background-color: red; } </style>

src/slot/SlotFather.vue:

<template> <div class="slotFather"> <h1>默认插槽</h1> <MyBtn>提交</MyBtn> <MyBtn>保存</MyBtn> <MyBtn> <span style="color: blue;">确认</span> <br /> <button>测试</button> </MyBtn> <MyBtn /> </div> </template> <script lang='ts' setup name='SlotFather'> import MyBtn from '@/components/MyBtn.vue'; </script> <style scoped> .slotFather { background-color: moccasin; color: black; }
Vue3开发极简入门(18):插槽Slot

具名插槽

MyBtn2.vue:

<template> <div> <slot name="beforeBtn"></slot> </div> <button class="gradient-button"> <slot name="btnText">默认内容</slot> </button> </template> <script lang='ts' setup name='MyBtn2'> </script> <style scoped> .gradient-button { display: inline-block; padding: 10px 20px; font-size: 16px; color: white; text-align: center; text-decoration: none; border-radius: 5px; border: none; cursor: pointer; background: linear-gradient(to right, green, darkgreen); } </style>

SlotFather.vue:

<h1>具名插槽</h1> <MyBtn2> <template #beforeBtn> <span style="color: red;">前置内容</span> </template> <template #btnText>提交</template> </MyBtn2>

说明:

跟上面的默认插槽结合看,代码很明晰了,不解释了。

其实写法应该是<template v-slot:beforeBtn>,但是可以简写<template #beforeBtn>

Vue3开发极简入门(18):插槽Slot

条件插槽

有时候可以根据插槽是否存在来决定是否渲染内容,例如上面的beforeBtn,如果父组件不传相应内容,就不渲染。

MyBtn2.vue:

<template> <div v-if="$slots.beforeBtn"> <slot name="beforeBtn"></slot> </div> <button class="gradient-button"> <slot name="btnText">默认内容</slot> </button> </template>

SlotFather.vue:

<h1>条件插槽</h1> <MyBtn2> <template #btnText>保存</template> </MyBtn2>
Vue3开发极简入门(18):插槽Slot

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/183644.html

(0)
上一篇 2025-07-18 08:26
下一篇 2025-07-18 08:33

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信