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>

效果图

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值