Vue插槽,是学习vue中必不可少的一节,下面以几个方面来说下
一、插槽内容
其实可以用一句话概括:插槽内可以是任意内容。
先看一下下面的代码:声明一个child-component
组件,
如果现在我想在<child-component></child-component>
内放置一些内容,结果会是怎样?
<div id="app">
<child-component></child-component>
</div>
<script>
Vue.component('child-component',{
template:`
<div>Hello,World!</div>
`
})
let vm = new Vue({
el:'#app',
data:{
}
})
</script>
<child-component>你好</child-component>
输出内容还是在组件中的内容,在 内写的内容没起作用。
这就是插槽出现的作用。
我们现在给组件增加一个插槽
我们在内写的"你好"就起作用了
Vue.component('child-component',{
template:`
<div>
Hello,World!
<slot></slot>
</div>
`
})
到现在,我们知道了什么是插槽:
插槽就是Vue实现的一套内容分发的API,将元素作为承载分发内容的出口。
这句话的意思就是,没有插槽的情况下在组件标签内些一些内容是不起任何作用的,当我在组件中声明了slot元素后,在组件元素内写的内容就会跑到它这里了!
二、具名插槽
具名插槽,就是给这个插槽起个名字
在组件中,我给插槽起个名字,一个名字叫"one",一个名字叫"two",还有一个不起名字。
然后再内,slot属性对应的内容都会和组件中name一一对应。
而没有名字的,就是默认插槽
<div id="app">
<child-component>
<template slot="one">
哈哈哈哈哈
</template>
<template slot="two">
呵呵呵呵呵
</template>
<div>
我是默认的插槽
</div>
</child-component>
</div>
<script>
Vue.component('child-component',{
template:`
<div>
<h4>这个世界不仅有一和二</h4>
<slot name="one"></slot>
<div style="height:1px;background-color:red;"></div>
<slot name="two"></slot>
<div style="height:1px;background-color:red;"></div>
<slot></slot>
</div>
`
})
let vm = new Vue({
el:'#app',
data:{
}
})
</script>