vue二十五:vue基础之slot插槽和具名插槽

定义组件

使用场景1:如果想要动态的给child组件的dom结构添加节点,则需使用插槽。直接添加是无效的

定义插槽

使用场景1:如定义一个轮播组件,不固定轮播的内容,轮播内容按使用的场景临时添加

使用

使用场景2:使用插槽实现在组件1上控制组件2是否展示

具名插槽,在预留了多个插槽时使用

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<!-- <navbar>-->
<!-- <button @click="isShow=!isShow">navbar-button</button>-->
<!-- </navbar>-->
<!-- <sidebar v-show="isShow"></sidebar>-->

<child>
<div slot="slot1">添加的div节点1</div>
<div slot="slot2">添加的div节点2</div>
</child>

<!-- <swiper>-->
<!-- <li v-for="data in datalist">-->
<!-- {{ data }}-->
<!-- </li>-->
<!-- </swiper>-->


</div>

<script>
Vue.component('child', {
template: `
<div>
<slot name="slot1"></slot>
child
<slot name="slot2"></slot>
</div>`
})

// 轮播组件
Vue.component('swiper', {
template: `
<div>
<ul>
<slot></slot>
</ul>
</div>`
})
new Vue({
el: "#app",
data: {
datalist: ['111', '222', '333']
}
})

// Vue.component('navbar', {
// template: `
// <div>
// navbar
// <slot></slot>
// </div>`
// })
// Vue.component('sidebar', {
// template: `
// <div>
// <ul>
// <li>1111</li>
// <li>2222</li>
// </ul>
// </div>`
// })
// new Vue({
// el: "#app",
// data: {
// isShow: false
// }
// })


</script>
</body>
</html>
讨论群:249728408
原文地址:https://www.cnblogs.com/zhongyehai/p/12389837.html