一、vue插槽简单用法
<!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">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>插槽</title>
</head>
<body>
<div id="app">
<div>父组件</div>
<com>
<div>
插入子组件的标签
</div>
</com>
</div>
<script>
var vm = new Vue({
el:"#app",
components: {
"com" : {
template:"<h2>子组件<slot></slot></h2>"
}
}
})
</script>
</body>
</html>
页面效果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f3057cc3e68f8df4eb95c310fc645f41.png)
二、具名插槽用法
<!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">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>具名插槽</title>
</head>
<body>
<div id="app">
<com>
<template v-slot:header>
<h1>标题</h1>
</template>
<template v-slot:main>
<h2>内容</h2>
</template>
<template v-slot:footer>
<h3>底部内容</h3>
</template>
</com>
</div>
<script>
var vm = new Vue({
el:"#app",
data () {
return {
info:1
}
},
components: {
"com" : {
template:`
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot name="main"></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
`
}
}
})
</script>
</body>
</html>
页面效果:
![具名插槽](https://i-blog.csdnimg.cn/blog_migrate/213501a3ff17b2022140448fd0a704f3.png)
三、作用域插槽
<!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">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>作用域插槽</title>
</head>
<body>
<div id="app">
<com>
<template v-slot:default="slotProps">
{{ slotProps.names }} {{ slotProps.age }}
</template>
</com>
</div>
<script>
var vm = new Vue({
el : "#app",
data(){
return {
}
},
components: {
com : {
data(){
return {
names:"张三",
age:40
}
},
template:`<h2>子组件内容<slot :names="names" :age="age"></slot></h2>`
}
}
})
</script>
</body>
</html>
页面效果:
![作用域插槽](https://i-blog.csdnimg.cn/blog_migrate/bef1251990a8a64dd5d75076b3a1edd1.png)