VUE3 学习笔记(9):VUE 插槽的概念、基本应用、传值

在调用子组件时,我们希望把父组件的HTML传给子组件,那么在引用子组件内部进行定义,然后子组件通过slot标签进行接收

基本示例

父 app.vue

<!--内容控制-->
<template>

  <test>
    <div>
      <p>{{name}}</p>
      <p>{{age}}</p>
    </div>
  </test>

</template>
<!--JS 控制-->
<script>

import test from "@/components/test.vue";


export default {
  components: {test},
  data() {
    return {
      name: '李四',
      age: 100
    }
  }

}
</script>

子 test.vue

<template>
  <div>
    <p>测试插槽:</p>
    <slot></slot>
  </div>
</template>
<script setup lang="ts">
</script>

自定义插槽

有时我们并不需要把相关需要的信息全部传过去或者需要根据条件进行局部显示,那么需要通过<template v-slot:命名>(也可以#命名)定义插槽进行命名,然后插槽时指定<slot name="命名"></slot>来实现。

父 app.vue

<!--内容控制-->
<template>

  <test>
    <template v-slot:ProName>
      <div>
        <p>{{name}}</p>
      </div>

    </template>
    <!-- 也可以如下命名   -->
    <template #ProAge>
      <div>
        <p>{{age}}</p>
      </div>

    </template>

  </test>

</template>
<!--JS 控制-->
<script>

import test from "@/components/test.vue";


export default {
  components: {test},
  data() {
    return {
      name: '李四',
      age: 100
    }
  }

}
</script>

子 test.vue

<template>
  <div>
    <p>测试插槽:</p>
    <slot name="ProName"></slot>
    <br>
    <slot name="ProAge"></slot>
  </div>
</template>

子组件反向对父组件进行传值

有时我们会需要把子组件的数据要传回给父组件(反向传值),子组件绑定并值并命名,

父组件通过v-slot="命名"的接收。

子 test.vue

<template>
  <div>
    <p>测试插槽:</p>
    <slot name="ProName"></slot>
    <br>
    <slot name="ProAge"></slot>
    <br>

    <slot :msg="sex"></slot>
    <slot name="ProBthDay" :BthDay="BthDay"></slot>
  </div>
</template>
<script >
export default {
  data() {
    return {
      sex: '男',
      BthDay: '1999-01-01'
    }
  }
}
</script>

父 app.vue

<!--内容控制-->
<template>

  <test>
    <template v-slot:ProName>
      <div>
        <p>{{name}}</p>
      </div>

    </template>
    <!-- 也可以如下命名   -->
    <template #ProAge>
      <div>
        <p>{{age}}</p>
      </div>
    </template>

    <template v-slot="ProSex" >
      <div>
        <p>接收到:{{ProSex.msg}}</p>
      </div>
    </template>

    <template #ProBthDay ="ProBthDay" >
      <div>
        <p>接收到:{{ProBthDay.BthDay}}</p>
      </div>
    </template>


  </test>

</template>
<!--JS 控制-->
<script>

import test from "@/components/test.vue";


export default {
  components: {test},
  data() {
    return {
      name: '李四',
      age: 100
    }
  }

}
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值