Vue slot具名插槽和props

本文介绍了Vue.js中的具名插槽及其用法,通过示例展示了如何在子组件中定义具名插槽并由父组件控制内容填充。同时,详细讲解了props的单向数据流,包括基本用法、应用场景以及props的动态绑定和验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

slot 具名插槽

示例

props单向数据流

基本用法:

基本应用场景:

实例


slot 具名插槽

what : 在子组件中定义插槽时,给对应的插槽分别起个名字,方便后边插入父组件将根据name来填充对应的内容

why : 为了让组件具备更强的通用性,不将自己暗中的内容限制为固定的div、span等元素,则可使用具名插槽

how : 插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制.

语法: <slot name = '名称'>默认值</slot>,

示例

在子组件 StuSlot.vue中定义两个具名插槽

<template>
  <div class="about">
    <h1>This is a Children page</h1>
    <!-- 给插槽添加name属性,便成为具名插槽 -->
    <!-- 定义两个具名插槽-->
    <slot name="one"></slot>
    <slot name="two"></slot>
  </div>
</template>

在父组件App.vue中:

为验证,子组件中的插槽可以填充任何结构的内容,所以专门在one插槽中插入一个组件,而在two插槽就单纯插入一串普通的数据

<template>
  <div id="about">
    <h1>This is a Parent page</h1>

    <StuSlot>

    <template v-slot:one>
      <p>one 插槽</p>
    </template>

    <template v-slot:two>
      two插槽
    </template>
    
  </StuSlot>
  </div>
  </template>
  
  <script>
  import StuSlot from './components/StuSlot.vue'
  export default {
    components:{
          StuSlot
      }
  }
  </script>
  
  <style>
  
  </style>

效果

 并且,子组件可以定义多个同名的具名插槽:

<template>
  <div class="about">
    <h1>This is an Children page</h1>
    <!-- 给插槽加了个name属性,就是所谓的具名插槽了 -->
    <slot name="one"></slot>
    <slot name="two"></slot>
    <slot name="two"></slot>
  </div>
</template>

props单向数据流

基本用法:

  • 在父组件中的data中定义值
  • 在子组件中使用props声明要引用哪个值
  • 父组件的template中要在子组件标签上绑定
  • 在template模板中,要使用中划线写法;在script脚本中使用小驼峰

基本应用场景:

  • 静态props:静态即传入的值不变化,直接在父组件中定义,子组件中使用
  • 动态props:动态即传入的值会变化,父组件中要动态地绑定父组件的数据
  • props验证:验证传入的props参数的数据规格,如果不符合数据规格则发出警告,注意这个数据类型包含所有的数据类型,如基本类型和引用类型;                                                             还可以在验证中加入自定义验证函数,当返回false时则发出警告

实例

Person.vue:

<template>
    <div class="props-container">
        <h1>个人信息</h1>
        <h2>姓名:{{name}}</h2>
        <h2>性别:{{sex}}</h2>
        <h2>年龄:{{age}}</h2>
        <h2>我的兴趣爱好是:</h2>

        <ul>
            <li v-for="(item,index) in interest" :key="index">{{item}}</li>
        </ul>
    </div>
</template>

<script>
export default {
    name:'',
    props:['name','age','sex','interest']
}
</script>

<style>
.props-container {
    border: 1px solid orange;
    width: 300px;
    background-color: yellowgreen;
    padding: 10px;
}
h1,
h2{
    margin: 0;
}
</style>

App.vue

<template>
  <div id="about">
<!-- 使用组件 -->
    <Person :name="'胡图图'" :age="6" :sex="'男'" :interest="['羽毛球','吉他','桌球']"></Person>
  </div>
</template>
  
  <script>
  // 导入组件
  import Person from './components/person.vue'
  export default {
    // 注册组件
    components:{
          Person
      },
      //传值
    data(){
      return{
        name:"胡英俊"
    }
  }
}

  </script>

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值