在 2.6.0 中,vue为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。目前 slot 与 slot-scope 这两个特性暂时还未被移除。
新版本 只能在 template 上绑定(特别注释)
具名插槽
(子组建 和老版本是一样的写法)
// 组件 (子组建 和老版本是一样的写法)
Vue.component('lv-hello', {
template: `
<div>
<slot name="header"></slot>
<h1>我的天呀</h1>
</div>
`
})
<div id="app">
<!-- 老版本使用具名插槽 -->
<lv-hello>
<p slot="header">我是头部</p>
</lv-hello>
<!-- 新版本使用具名插槽 -->
<lv-hello>
<!-- 注意:这块的 v-slot 指令只能写在 template 标签上面,而不能放置到 p 标签上 -->
<template v-slot:header>
<p>我是头部</p>
</template>
</lv-hello>
</div>
具名插槽的(上面的 缩写)
将 v-slot: 替换成 # 号
(注意:这块的 v-slot 指令只能写在 template 标签上面,而不能放置到 p 标签上)
<div id="app">
<lv-hello>
<template #header>
<p>我是头部</p>
</template>
<!-- 注意: #号后面必须有参数,否则会报错。即便是默认插槽,也需要写成 #default -->
<template #default>
<p>我是默认插槽</p>
</template>
</lv-hello>
</div>
作用域插槽
所谓作用域插槽,就是让插槽的内容能够访问子组件中才有的数据。
需要 在<slot> 上绑定数据
// 子组建
Vue.component('lv-hello', {
data: function () {
return {
firstName: '张',
lastName: '三'
}
},
template: `
<div>
<slot name="header" :firstName="firstName" :lastName="lastName"></slot>
<h1>我的天呀</h1>
</div>
`
})
注意:这块的 v-slot 指令只能写在 template 标签上面,而不能放置到 p 标签上
<div id="app">
<!-- 老版本使用具名插槽 -->
<lv-hello>
<p slot="header" slot-scope="hh">我是头部 {{ hh.firstName }} {{ hh.lastName }}</p>
</lv-hello>
<!-- 新版本使用具名插槽 -->
<lv-hello>
<!-- 注意:这块的 v-slot 指令只能写在 template 标签上面,而不能放置到 p 标签上 -->
<template v-slot:header="hh">
<p>我是头部 {{ hh.firstName }} {{ hh.lastName }}</p>
</template>
</lv-hello>
</div>
新版的具名插槽 和 作用域插槽 ,
ps:(子组件的数据 在 '=hh')
v-slot:header
v-slot:header="hh"
一句话概括就是v-slot :后边是插槽名称,=后边是组件内部绑定作用域值的映射。
<testSlot :father_data="syncData">
<template #test="hh">
{{hh.a}} and {{hh.b}}
</template>
</testSlot>
setTimeout(()=> {
this.syncData = {
a: 456
}
console.log(this.syncData, "查看数据");
},3000)
// 子
<slot name="test" :a="father_data.a" :b="data.b"></slot>
props: ["father_data"],
data: {
a: 1,
b: 2,
}
issues:
antd vue是如何实现slot-scope传多参的?(无人解答)
<template slot="customRender"slot-scope="text, record, index, column">
自己项目中的使用
父组建
<tablec ref="tablec" :columns="columns" :requestObj="requestObj" @Ok="onMessage">
<span slot="#" slot-scope="{index}">
{{index}}
</span>
<span slot="taskStatus" slot-scope="{text,index,data}">
{{text}}
</span>
</tablec>
子组建
<section>
<div class="list_tr" @click="to_router(val)" v-for="(val, x) in dataSource" :key="x">
<div v-for="(item, i) in columns" :key="i" :style="`text-align:${item.align};margin-left: 15px;${'width' in item && item.width? 'width: '+item.width+'px' : 'flex:1'}`">
<span v-if="'scopedSlots' in item && item.scopedSlots == '#'">
<slot name="#" :index="`${(pageNo-1)*limit+(x+1)}`"></slot>
</span>
<span v-else-if="'scopedSlots' in item && item.scopedSlots">
<slot :name="item.scopedSlots" :text="val[item.dataIndex]" :index="x" :data="val"></slot>
</span>
<span v-else>{{val[item.dataIndex]}}</span>
</div>
</div>
</section>
网友评论