写这篇文章是由于本身在做用域插槽这里用了较多时间,而后在论坛看的大可能是目前已废弃的写法。
本文的例子参考下面这篇文章的例子css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue2.6.0做用域插槽</title> <script src="https://cdn.bootcss.com/vue/2.6.10/vue.common.dev.js"></script> </head> <body> <div id="app2"> <!-- 组件使用者只需传递users数据便可 --> <my-stripe-list :items="users" odd-bgcolor="#D3DCE6" even-bgcolor="#E5E9F2"> <!-- props对象接收来自子组件slot的myIndex对象,解构 --> <!-- 若是myIndex不加{},则能够是任意值,例如js,则下边[]内的myIndex都替换为js.myIndex --> <template v-slot:leslie="{myIndex}"> <span>{{users[myIndex].id}}</span> <span>{{users[myIndex].name}}</span> <span>{{users[myIndex].age}}</span> <!-- 这里能够自定[编辑][删除]按钮的连接和样式 --> <a :href="'#edit/id/'+users[myIndex].id">编辑</a> <a :href="'#del/id/'+users[myIndex].id">删除</a> </template> </my-stripe-list> </div> <script> Vue.component('my-stripe-list', { /*slot的$index能够传递到父组件中*/ template: ` <div> <div v-for="(item, index) in items" style="line-height:2.2;" :style="index % 2 === 0 ? 'background:'+oddBgcolor : 'background:'+evenBgcolor"> <slot name="leslie" :myIndex="index"></slot> </div> </div> `, props: { items: Array, oddBgcolor: String, evenBgcolor: String } }); new Vue({ el: '#app2', data: { users: [ {id: 1, name: '张三', age: 20}, {id: 2, name: '李四', age: 22}, {id: 3, name: '王五', age: 27}, {id: 4, name: '张龙', age: 27}, {id: 5, name: '赵虎', age: 27} ] } }); </script> </body> </html>
子组件能够不要名字: <slot name="leslie" :myIndex="index"></slot>
对应的父组件的写法为: <template v-slot="{myIndex}">
其实仔细一看,做用域插槽仍是比较简单的,关键就是一句话: <template v-slot:leslie="{myIndex}">html