Vue学习:19.插槽实例
来个简单示例练练手吧。
实例:插槽实例
思路
在封装表格组件时,通常使用默认插槽和作用域插槽来处理固定的自定义结构。
代码
根组件(APP.vue)
<template>
<div>
<MyTable :data="list1">
<!-- 使用插槽 -->
<!-- 3.通过template #插槽名=‘变量名’接收数据 -->
<template #default="obj">
<button @click="del(obj.row.id)">删除</button>
</template>
</MyTable>
<MyTable :data="list2">
<!-- v-slot: 等价于 # -->
<template v-slot:default="{ row }">
<button @click="show(row)">查看</button>
</template>
</MyTable>
</div>
</template>
<script>
import MyTable from './components/MyTable.vue'
export default {
data(){
return{
list1:[
{id:1, name:'赵天明', age:25},
{id:2, name:'李翔飞', age:22},
{id:3, name:'吴国基', age:24},
],
list2:[
{id:1, name:'赵天明', age:25},
{id:2, name:'李翔飞', age:22},
{id:3, name:'吴国基', age:24},
]
}
},
methods:{
del(id){
// console.log(id)
this.list1 = this.list1.filter(item => item.id !== id)
},
show(row){
// console.log(row)
// 使用模版字符${}需要反引号-``(波浪线那个)
alert(`姓名: ${row.name}; 年龄: ${row.age}`)
}
},
components:{
MyTable
}
}
</script>
<style>
</style>
子组件
<template>
<div>
<table>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="item.id">
<td>{{ index+1 }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<!-- 定义插槽 -->
<!-- 1.以添加属性的方式,传值 -->
<slot :row="item" msg="测试文本"></slot>
<!-- 2.将所有属性添加到一个对象 -->
<!-- {
row:{id:2, name:'李翔飞', age:24},
msg:'测试文本'
} -->
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props:{
data:Array
}
}
</script>
<style scoped>
table{
margin-top: 20px;
border-collapse: collapse;
text-align: center;
}
th,td{
width: 80px;
height: 50px;
line-height: 50px;
border: 2px solid rgb(163, 161, 161);
}
th{
background-color: blue;
color: #fff;
}
</style>