插槽<slot>
不难理解,就是子组件提供了可替换模板,父组件能够更换模板的内容。
具名插槽,让子组件内能够提供多个插槽,父组件就能够对应替换多块的内容。
做用域插槽理解起来比较难,官方文档比较简单,网上又实在没有找到很好的解释,做为初学者我花了点时间,这里分享一下个人理解,也方便本身记忆。html
做用域插槽表明性的例子就是列表组件,一个列表组件,写一个props接收数据,而后组织好ul、li标签,写好样式,就像这样
<template> <div> <ul> <li v-for="(item,index) in items">{{index+1}}、《{{item.name}}》{{item.author}}</li> </ul> </div> </template> <script> export default{ name: 'child', props: { items: { type: Array } } } </script>
父组件只须要传入数据便可
<template> <div v-cloak> <child :items="books"></child> </div> </template> <script> import child from './child'; export default{ name: 'father', data(){ return{ books: [ { name: '三体', author: '刘慈欣' }, { name: '解忧杂货店', author: '东野圭吾' }, { name: '爱与寂寞', author: '吉杜·克里希那穆提' } ] } }, components: { child } }; </script>
生成的效果就是这样的
在其它地方使用这个子组件,生成的效果样式是同样的,若是但愿在另外一个父组件下有不同的样式,这个子组件是无法作到的。例如我想让其在另外一父组件下时,序号是红色,书名要加粗,做者名字是斜体。
让咱们修改一会儿组件:
<template> <div> <ul> <slot v-for="(item,index) in items" :index="index" :title="item.name" :author="item.author"> <li>{{index+1}}、《{{item.name}}》{{item.author}}</li> </slot> </ul> </div> </template>
原来的<li>用插槽<slot>包起来,v-for也与<slot>绑定, 在没有父组件插入内容的状况下默认显示这里<li>的内容。在<slot>上使用v-bind,将index、name、author动态数据传入插槽。
这时父组件这样写:
<template> <div v-cloak> <child :books="books"> <template slot-scope="child"> <li><span style="color:red">{{child.index+1}}、</span><b>《{{child.title}}》</b><i>{{child.author}}</i></li> </template> </child> </div> </template>
最里面的template标签至关于父组件从新定义的模板, 经过child这个临时变量,访问插槽里的子组件传入的数据,最后生成的效果:
最后总结一下,做用域插槽给了子组件将数据返给父组件的能力,子组件同样能够复用,同时父组件也能够从新组织内容和样式spa