作用域slot的理解与应用

简介

作用域slot可以简单理解为可以传递参数的slot;通过在子组件slot标签上绑定数据,达到在父组件获取子组件信息的作用。

用法

1、子组件中确定slot的位置,并将需要传递给父组件显示的信息绑定到slot标签上。

<template>
  <div class="wrap">
    <ul
      class="list"
      style="border: 1px solid #000; list-style: none; padding: 0"
    >
      <li
        v-for="item in parentData"
        style="
          list-style: none;
          height: 50px;
          background: #eee;
          border: solid 1px #000;
          line-height: 50px;
        "
      >
      <!-- todo绑定的值即为发送给父组件的信息 -->
        <slot name='header' :todo="item"></slot>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "sonComponent",
  props: {
    parentData: {
      type: Array,
      require: true,
    },
  },
  data() {
    return {};
  },
  methods: {},
};
</script>

2、父组件上通过 slot-scope来获取子组件传递过来的值,并显示出来。需要注意的是slot-scope获取的值并非子组件上直接绑定的值,而是一个包含子组件绑定值的对象,所以需要用“.”来获取。

<template>
  <div class="wrap">
    <son :parentData="pData">
        <!-- 通过slot-scope获取子组件传递的值 -->
       <!--此种写法已废弃-->
      <!-- <template slot-scope="data"> -->
      <template v-slot:header={todo}>
        {{ todo.name }}
      </template>
    </son>
  </div>
</template>

<script>
import son from "./son.vue";
export default {
  components: { son },
  data() {
    return {
      pd: "hello",
      pData: [
        { name: "henry", age: "23", gender: "male" },
        { name: "jason", age: "27", gender: "male" },
        { name: "jasper", age: "25", gender: "male" },
        { name: "tony", age: "23", gender: "male" },
        { name: "lily", age: "21", gender: "female" },
      ],
    };
  },
};
</script>

<style>
</style>

应用场景

当父组件需要更改子组件的显示内容但又需要用到子组件的信息时就会用到作用域slot,例如:在表格的单元格内添加按钮来编辑或删除单元格内容。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值