vue的slot是子组件向父组件提供html自定义模版,具体做法是子组件中定义slot模版,然后在父组件中使用template去填充子组件的slot部分,子组件可以通过在slot上添加属性给父组件传递数据。
主要使用在拓展组件上,比如表格组件,让父组件可以自定义每一行的不同情况下的按钮,而子组件只需要关心一些通用的功能、布局和样式,业务逻辑部分在父组件处理,常用于一些vue的ui组件库。
具体写法可以参考例子,v-slot:slotName是vue2.6以上的写法,旧写法是slot=“slotName” slot-scope=“data”,在例子中可以看到父组件的template的位置与子组件中填充的位置没有关系,会固定按照子组件的slot位置进行渲染。
例子如下:父组件传递给子组件一个数组,然后子组件将每一个数组项传递回父组件。
<template>
<div id="app">
<cus-table :list="list">
<template>默认slot</template>
<template>默认slot2</template>
<template v-slot:title>
<p>具名slot</p>
</template>
<template v-slot:oprs="{item,index}">
<button @click="addCount(item,index)">button</button>
</template>
</cus-table>
</div>
</template>
<script>
import CusTable from "./components/CusTable.vue";
export default {
name: "App",
components: {
CusTable
},
data: () => {
return {
list: [
{
id: 0,
content: 0
},
{
id: 1,
content: 0
},
{
id: 2,
content: 0
},
{
id: 3,
content: 0
}
]
};
},
methods: {
addCount(item, index) {
this.list[index].content += 1;
}
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件CusTable:
<template>
<div>
<slot name="title"></slot>
<slot></slot>
<ol>
<li class="list-item" v-for="(item,index) in list" :key="item.id">
<span class="item-content">{{item.content}}</span>
<slot name="oprs" :item="item" :index="index"></slot>
</li>
</ol>
</div>
</template>
<script>
export default {
props: {
list: {
type: Array
}
}
};
</script>
<style>
li {
list-style: none;
}
.list-item:nth-child(odd) {
background: #f1f1f1;
}
.item-content {
display: inline-block;
width: 100px;
}
</style>
效果图: