前言:使用的插槽是2.6.0以后的,以前的废弃用法,暂且不谈,要了解看文档
一、具名插槽
如下:(使用v-slot:xxx语法) 一个不带 name 的 出口会带有隐含的名字“default”。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>slot</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
<div id='root'>
<children>
<template v-slot:header>
头部
</template>
中间内容 // 等同于 <template v-slot:default>中间内容</template>
<template v-slot:footer>
底部
</template>
</children>
</div>
</body>
<script>
Vue.component('children', {
template: `
<div class="container">
<header>
<slot name='header'></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name='footer'></slot>
</footer>
</div>`
})
var vm = new Vue({
el: '#root'
})
</script>
</html>
二、作用域插槽
如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>slot</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
<div id='root'>
<current-user>
<template v-slot='slotProps'>
{{ slotProps.user.firstName }}
</template>
</current-user>
</div>
</body>
<script>
Vue.component('current-user', {
template: `
<span>
<slot v-bind:user='user'>{{ user.firstName }}</slot>
</span>`,
data() {
return {
user: {
firstName: '李'
}
}
}
})
var vm = new Vue({
el: '#root',
})
</script>
</html>
四、动态插槽名
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
</base-layout>
五、具名插槽缩写
具名插槽v-slot:可以用#代替
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>slot</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
<div id='root'>
<children>
<template #header>
头部
</template>
中间内容 等同于 <template #default>中间内容</template>
<template #footer>
底部
</template>
</children>
</div>
</body>
<script>
Vue.component('children', {
template: `
<div class="container">
<header>
<slot name='header'></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name='footer'></slot>
</footer>
</div>`
})
var vm = new Vue({
el: '#root'
})
</script>
</html>