vue2.0里面slot插槽的用法探究

插槽在vue里面也是可以数据通信的,但是很多人却忽略了这个!今天我们研究一下slot的使用方法!

请添加图片描述

    <Lists :datas="['奶茶', '水果', '披萨']"></Lists>
    <Lists :datas="['苹果', '香蕉', '橘子']" :render="render"></Lists>
    <hr />
    <Lists1 :datas="['苹果', '香蕉', '橘子']">
      <template #a="obj">
        <!--  具名插槽的写法 -->
        <!-- <template v-slot:a= -->
        <span>{{ obj.item }}</span>
      </template>
    </Lists1>
import Lists from "../components/Lists";
import Lists1 from "../components/Lists1";
export default {
 components: {
   Lists,
   Lists1,
 },
 methods: {
   render(h, data) {
     return <span>{data}</span>;
   },
 },
};
</script>

List.vue

<template>
  <div>
    <template v-for="(item, index) in datas">
      <li :key="index" v-if="!render">
        {{ item }}
      </li>
      <ListItem
        v-else
        :item="item"
        :key="`a${index}`"
        :render="render"
      ></ListItem>
    </template>
  </div>
</template>

<script>
import ListItem from "./ListsItem";
export default {
  props: {
    datas: {
      type: Array,
      default: () => [],
    },
    render: {
      type: Function,
    },
  },
  components: {
    ListItem,
  },
};
</script>

<style lang="scss" scoped></style>

listItem.vue

export default {
  props: {
    render: {
      type: Function,
    },
    item: {
      type: String,
    },
  },
  render(h) {
    console.log(h);
    return this.render(h, this.item);
  },
};

lists1.vue

<template>
  <div>
    <template v-for="(item, index) in datas">
      <li :key="index" v-if="!render">
        <slot name="a" :item="item" :a="index"></slot>
      </li>
      <ListItem
        v-else
        :item="item"
        :key="`a${index}`"
        :render="render"
      ></ListItem>
    </template>
  </div>
</template>

<script>
import ListItem from "./ListsItem";
export default {
  props: {
    datas: {
      type: Array,
      default: () => [],
    },
    render: {
      type: Function,
    },
  },
  components: {
    ListItem,
  },
};
</script>

<style lang="scss" scoped></style>

这样就是插槽在组件中的使用方法!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值