插槽slot与事件event

常见的一些事件event

change 用户确定选定的值时触发

blur 在组件失去焦点时触发

focus 在组件获得焦点时触发

vue中的插槽slot

slot是一个插槽出口,标志父元素的插槽内容将在哪里被渲染

下方是vue官方案例

1
2
3
4
5
<FancyButton>

click me!<插槽内容>

</FancyButton>

模板的具体代码

1
2
3
4
5
<button class="fancy-btn">

<slot></slot> *<!-- 插槽出口 -->*

</button>

最终渲染出的dom为

1
<button class="fancy-btn">Click me!</button>
插槽可定义默认内容

如果父组件中没用提供插槽内容时将会被渲染为默认

1
2
3
4
5
6
<button type="submit">
<slot>
Submit <!-- 默认内容 -->
</slot>

</button>
具名插槽
1
2
3
4
5
6
7
8
9
10
11
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>

如果没有提供name的出口会隐式地命名为default

1
2
3
4
5
6
7
<BaseLayout>
<template v-slot:header>
*<!-- header 插槽的内容放这里 -->*
</template>
*<!-- 下面是简写模式 -->*
<template #header></template>
</BaseLayout>

而且如果默认插槽可以不加template直接写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<BaseLayout>

<template #header>
<h1>Here might be a page title</h1>
</template>


<!-- 隐式的默认插槽 -->

<p>A paragraph for the main content.</p>
<p>And another one.</p>

<template #footer>
<p>Here's some contact info</p>
</template>

</BaseLayout>
动态插槽名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<base-layout>

<template v-slot:[dynamicSlotName]>
...
</template>


<!-- 缩写为 -->

<template #[dynamicSlotName]>
...
</template>

</base-layout>
作用域插槽
1
2
3
4
5
6
7
8
<!-- <MyComponent> 子元素的模板 -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>
<!-- 父元素中调用子元素的值 -->
<MyComponent v-slot="slotProps">
{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>