插槽是指HTML起始标签与结束标签中间的部分,通常在使用div标签时,其内部的插槽位置既可以放置要显示的文案,又可以嵌套放置其他标签,例如:

1
2
3
4
<div>文案部分</div>
<div>
<button>按钮</button>
</div>

插槽的核心作用是将组件内部的元素抽离到外部进行实现,在进行自定义组件的设计时,良好的插槽逻辑可以使组件的使用更加灵活。


基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue组件插槽</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="Application">
<my-container>插槽内部</my-container>
</div>
<script>
const App = Vue.createApp({ })
const containerComponent = {
template: `<div style="border-style:solid;border-color:red; border-width:10px">
<slot>默认内容</slot>
</div>`
}
App.component("my-container", containerComponent)
App.mount("#Application")
</script>
</body>
</html>
  • 使用slot标签来指定插槽的位置
  • 可以为插槽添加默认内容(组件在使用时设置了插槽的内容,默认内容就不会被渲染)

(多)具名插槽的用法

  • 若要为插槽设置名称,则可以使用name属性来为其设置名称
  • 需要注意的是,在使用此组件时,要使用template标签来包装插槽内容,对于template标签,通过#(等价于v-slot)来指定与其对应的插槽位置。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue组件插槽</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="Application">
<my-container2>
<template #header>
<h1>这里是头部元素</h1>
</template>

<template #main>
<p>内容部分</p>
<p>内容部分</p>
</template>

<template #footer>
<p>这里是尾部元素</p>
</template>
</my-container2>
</div>
<script>
const App = Vue.createApp({
})
const container2Component = {
template:`<div>
<slot name="header"></slot>
<hr/>
<slot name="main"></slot>
<hr/>
<slot name="footer"></slot>
</div>`
}
App.component("my-container2", container2Component)
App.mount("#Application")
</script>
</body>
</html>