I believe that everyone who has used Vue has used the slot in
Vue more or less, but do you understand its usage? This article will bring you the basic use of slots and named slots in Vue. I hope it will be helpful to you!
⭐⭐
First introduction to slots:
div
, span
Wait for these elements; [Related recommendations: vuejs video tutorial]In other words, if we want to add new content to a component tag, then we need to declare a slot in the component, otherwise, the added New content will not be rendered
⭐⭐
Using slots:
slot
elements as slotsslot
tagUse slot case:
Parent component
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>
SubcomponentshowMessage.vue
<template> <h2>{{title}}</h2> <div class="content"> <slot> <p>我是默认值</p> </slot> </div> </template>
showMessage
, we give it a slot, App.vue
, we reuse showMessage
three times , once for button
, once for a label
, once without adding anything
one is the button
, one is a link
, is the default p label of the slot
##We can see that
element has a special
attribute: name;
without
name will have an implicit name
default;
tag and used ## in
template
#v-solt: Slot name named slot abbreviation
App.vue<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;"><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></pre><div class="contentsignin">Copy after login</div></div>
Subcomponent
NavBar.vue (You can adjust the color in the css, so I won’t put it here)
<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>
The effect achieved is the display corresponding to the slot So this is the role of the named slot
⭐⭐
Pass
v-slot: [dynamicSlotName]
way to dynamically bind a name;Ps: There are also scope slots, which I don’t understand very well yet, so I won’t write them down~
(Learning video sharing :
Web front-end developmentThe above is the detailed content of A brief analysis of the role of slots and named slots in Vue. For more information, please follow other related articles on the PHP Chinese website!