什么是插槽
插槽就是子组件中的提供给父组件应用的一个占位符,用<slot></slot> 示意,父组件能够在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。
根本应用
编写一个父组件
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Demo</title> <script src="https://unpkg.com/vue@next"></script></head><body> <div id="app"></div></body><script> const app = Vue.createApp({ template: ` <h2>父组件</h2>` }) const vm = app.mount("#app")</script></html>
再写一个子组件
app.component('son', { template: ` <div> <h3>子组件</h3> </div> `})
父组件调用子组件
const app = Vue.createApp({ template: ` <h2>父组件</h2><son />` })
插槽如何应用呢?只须要在子组件中退出<slot></slot>
,而后在父组件中应用。
app.component('son', { template: ` <div> <h3>子组件</h3> <slot></slot> </div> `})
const app = Vue.createApp({ template: ` <h2>父组件</h2><son>这是父组件要在子组件中显示的内容</son>` })
运行成果:
父组件子组件这是父组件要在子组件中显示的内容
插槽反对任何DOM元素,比方咱们增加style
款式
const app = Vue.createApp({template: ` <h2>父组件</h2><son><div style="color:red;font-size:25px">这是父组件要在子组件中显示的内容</div></son>` })
默认插槽
咱们如果须要子组件在任何状况下,都能渲染文本。咱们能够将默认文本放在<slot>标签内:
app.component('son', { template: ` <div> <h3>子组件</h3> <slot>子组件的默认内容</slot> </div> `})
当初应用父组件去调用:
const app = Vue.createApp({template: ` <h2>父组件</h2><son/>` })
运行成果:
父组件子组件子组件的默认内容
具名插槽
有的时候,咱们一个子组件须要多个插槽,例如:
app.component('son', { template: ` <div> <h3>公民根本信息</h3> <slot> <!--姓名--> </slot> <slot> <!--年龄--> </slot> <slot> <!--性别--> </slot> </div> `})
像这种状况,<slot>
有一个非凡的属性name
app.component('son', { template: ` <div> <h3>公民根本信息</h3> <slo name="name"> 姓名 </slot> <slot name="age"> 年龄 </slot> <slot name="sex"> 性别 </slot> </div> `})
如何应用呢?很简略只须要在DOM元素上,应用v-slot
注明应用的插槽名称:
const app = Vue.createApp({template: ` <h2>父组件</h2> <son> <template v-slot:name>小明</template> <template v-slot:age>7</template> <template v-slot:sex>男</template> <son/>` })
运行成果:
父组件公民根本信息小明7男
v-slot:name
这种语法能够简写成#name
,代码如下:
const app = Vue.createApp({template: ` <h2>父组件</h2> <son> <template #name>小明</template> <template #age>7</template> <template #sex>男</template> <son/>` })
注:只有呈现多个插槽,所有的插槽应用残缺的基于 <template>
的语法。
插槽的作用域
有时让插槽内容可能拜访子组件中才有的数据是很有用的。
写一个子组件:
const app = Vue.createApp({data(){ return { list:['A','B','C'] }},template: `<div v-for="item in list">{{item}}</div>`})
父组件想应用子组件插槽中的值,能够应用:
绑定的模式进行传递,比方写成:item="item"
,具体的代码能够写成上面的样子。
const app = Vue.createApp({data(){ return { list:['A','B','C'] }},template: ` <div> <slot v-for="item in list" :item="item" /> </div>`})
写完后父组件中用v-slot="xxx"
的模式承受,接管后就能够应用了
const app = Vue.createApp({ template: ` <list v-slot="props"> <span>{{props.item}}</span> </list>`
留神这里的props
是子组件传递过去的数据都是对象,但你也能够应用任意你喜爱的名字。