组件内部能够使用插槽标记对<slot></slot>,添加插槽则可以在该组件标记对中放置数据。同样在插槽标记对内部同样可以使用自定义属性携带数据。插槽的使用可以让开发者比比较随心的为组件添加数据,可以提高组件的通用性。
组件中用好插槽难点在于其数据的传递过程,以下为插槽使用的例子代码:
Vue.component("myChart",{
template:`
<table>
<thead>
<tr>
<template v-for="(item,index) in theadDate">
<th><slot name="item" :item=item :index=index></slot></th>
</template>
</tr>
</thead>
<tbody>
<template v-for="(item,index) in tbodyDate">
<tr>
<slot name="body" :item=item :index=index></slot>
</tr>
</template>
</tbody>
</table>
`,
props:["theadDate","tbodyDate"]
}
组件代码的目的是建立一个表格,该表格有一行表头,多行表体,且每行存在多个单元格。在该代码中两处使用了slot标记对,标记对中均传入了数据item和index,且使用item与index自定义属性携带。
在组件使用中需要在使用插槽(添加了v-slot)中指定目标插槽的name取值来进行对接,同时自定义一个变量接收插槽中携带的数据。注意,插槽中可携带多个数据,均由这一个自定义变量接收,所以该变量是对象数据类型,并用点语法进行调配使用。调用代码如下:
<my-chart :thead-date="theadDate" :tbody-date="tbodyDate">
<template v-slot:item="sc">
<template v-if="sc.index===0">
<input type="checkbox">
</template>
<template v-else>
{{sc.item}}
</template>
</template>
<template v-slot:body="sc">
<td><input type="checkbox"></td>
<template v-for="(value,key,index) in sc.item">
<td>{{value}}</td>
</template>
<td><button>新增</button><button>删除</button></td>
</template>
</my-chart>
在该部分代码里数据传递流程大致如下:
使用插槽进行数据传递,可以在代码中定义自己想要的表单效果,而不是仅仅只渲染规定好的数据和结构,增加了组件的通用性。