【vue】使用插槽组件之间传递内容

1、使用插槽

父组件调用子组件使用双标签语法,在其中书写需要传递给子组件的内容

父组件

// Parent.vue

<template>
  <div>
    <TestChild>
      <div>{{ content }}</div>
    </TestChild>
  </div>
</template>

<script>
import TestChild from '@/components/TestChild'
export default {
  components: {
    TestChild
  },
  data() {
    return {
      content: '顾鸟'
    }
  }
}
</script>

子组件

// Child.vue

<template>
  <div>
    <slot></slot>
  </div>
</template>

展示效果
在这里插入图片描述

2. 具名插槽

v-slot: 可以简写成 #,子组件通过 name 指定接收父组件传递的内容
组件使用 slot 接受内容,但 slot 不能绑定事件,所以在外层包裹一个 span 标签,用来绑定事件

父组件

// Parent.vue

<template>
  <div>
    <TestChild>
      <template v-slot:name>
        <div>{{ name }}</div>
      </template>

      <template #age>
        <div>{{ age }}</div>
      </template>
    </TestChild>
  </div>
</template>

<script>
import TestChild from '@/components/TestChild'
export default {
  components: {
    TestChild
  },
  data() {
    return {
      name: '顾鸟',
      age: 18
    }
  }
}
</script>

子组件

// Child.vue

<template>
  <div>
    <span @click="handleClick">
      <slot name="name"></slot>
    </span>
    <slot name="age"></slot>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      alert('name')
    }
  }
}
</script>

效果展示(只有点击 顾鸟 才会弹窗)
在这里插入图片描述

3、作用域插槽

作用域插槽解决的问题:子组件的内容由父组件决定
:item=“item” 把子组件的数据传递给父组件,父组件通过 v-slot="{{item}}" 解构出数据,然后渲染
详细案例可以参考这里

父组件

<template>
  <div>
    <TestChild v-slot="{ item }">
      <div>{{ item }}</div>
    </TestChild>
  </div>
</template>

<script>
import TestChild from '@/components/TestChild'
export default {
  components: {
    TestChild
  }
}
</script>

子组件

<template>
  <div>
    <slot v-for="item in list" :item="item"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [1, 2, 3]
    }
  }
}
</script>

效果展示
在这里插入图片描述

不忘初心

参考链接:
https://www.jianshu.com/p/e10baeff888d

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值