先写一段简单的代码html
<div id="root"> <child content="<p>Dell</p>"></child> </div> Vue.component('child', { props: { content:String }, template: `<div> <p>hello</p> <div v-html="this.content"></div> </div>`, }) let vm = new Vue({ el: '#root' })
这种写法有两个问题:dom
p
标签外面会有一层div
,这个div
是没法去掉的,有人会想,能不能用template
代替,实际上是不能够的,在这里模版站位符是不能用的。content
传递的内容不少,代码就会变得很难阅读。当个人子组件有一部份内容,是根据父组件传递过来的dom
进行显示的话,这时候能够换一种语法。this
slot
<div id="root"> <child> <p>Dell</p> //这种语法看起来很是像,用子组件,我向里插入内容 </child> </div> Vue.component('child', { props: { content:String }, template: `<div> <p>hello</p> <slot></slot> //slot 标签显示的内容就是父组件向子组件插入进来的内容 </div>`, }) let vm = new Vue({ el: '#root' })
<p>Dell</p>
这种语法看起来很是像,用子组我向里插入内容,因此咱们把它叫作插槽。code
slot
标签显示的内容就是父组件向子组件插入进来的内容。component
经过插槽能够更方便的向子组件传递dom
元素,同时子组件只需经过slot
来使用就能够了。htm
slot
其余功能若是子组件里没有dom
元素,能够让它显示默认内容,以下:class
<slot>默认内容</slot>
若是如今有个需求是,header
和footer
是由外部引入的该怎么弄呢?以下语法
<div id="root"> <body-content> <div class="header" slot="header">header</div> <div class="footer" slot="footer">footer</div> </body-content> </div> Vue.component('body-content', { props: { content:String }, template: `<div> <slot name="header"></slot> <div class="content">content</p> <slot name="footer"></slot> </div>`, }) let vm = new Vue({ el: '#root' })
slot
标签name
属性对应的是组件中slot
属性,经过这种写法,能够在调用子组件时,一次性传递多个区域的dom
结构,在子组件里经过具名插槽来分别使用不一样部分的dom
结构模版