vue3中的Props

直接上案例:

父子组件中传递值

首先定义父组件:

<template>
  <child a="1" :b="1+1" c="list" :list="personList"/>
  <div class="boxStyle">
    <h3>我是父亲</h3>
  </div>
</template>

<script lang="ts" setup name="Father">
import { reactive } from "vue";
import child from "./child.vue";
import {type Persons } from "@/types/index"

//推荐指数*****
let personList = reactive<Persons>([
  {id:"1",name:"张三",age:18},
  {id:"2",name:"李四",age:19},
  {id:"3",name:"王五",age:20},
])

</script>

<style scoped>
.boxStyle {
  background-color: #5bcee8;
  border-radius: 10px;
  box-shadow: 0 0 10px #ccc;
  padding: 20px;
}
</style>

子组件:

<template>
<div class="boxChild">
    <h3>我是孩子</h3>
    <h4>{{ a }}</h4>
    <h4>{{ b }}</h4>
    <h4>{{ c }}</h4>
    <h4>{{ list }}</h4>
</div>

</template>

<script lang="ts" setup name="Child">
import { defineProps } from 'vue';

 defineProps(['a','b','c','list'])
</script>


<style scoped>
.boxChild {
    background-color: #c9e188;
    border-radius: 10px;
    box-shadow: 0 0 10px #ccc;
    padding: 20px;
}
</style>

测试界面:

解释:没有在子组件标签添加v-bind的元素,默认是字符串,并且不参与运算 ,因此在传参的时候需要加上v-bind

v-for的循环方式

如果,传递的对象值为一个数字时,其使用v-for循环时,默认是循环次数:

 

测试界面

 

当子界面,没有接受到父组件传入的参数时,默认是不会渲染界面的 

父子组件传值的场景:

接受父组件传递给子组件的值:

父组件:

<template>
  <div class="boxStyle">
    <h3>我是父亲</h3>
  </div>
  <child :list="personList"/>
  <child/>
</template>

<script lang="ts" setup name="Father">
import { reactive } from "vue";
import child from "./child.vue";
import {type Persons} from "@/types/index"

//推荐指数*****
let personList = reactive<Persons>([
  {id:"1",name:"张三",age:18},
  {id:"2",name:"李四",age:19},
  {id:"3",name:"王五",age:20},
])

</script>

子组件:

<template>
  <div class="boxChild">
    <h3>我是孩子</h3>
    <ul v-for="item in list" :key="item.id">
      <li>{{ item.name }}--{{ item.age }}</li>
    </ul>
    <hr>
  </div>
</template>

<script lang="ts" setup name="Child">
import { defineProps,withDefaults } from "vue";
import { type Persons } from "@/types";

//正常接受组件值
// defineProps(["a", "b", "c", "list","circle"]);

//接受list + 限制条件
// defineProps<{list:Persons}>()

//接受list + 限制条件 + 限制必要性(使用?可传可不传) + 指定默认值
// defineProps<{list?:Persons}>()

//推荐指数:*****
withDefaults(defineProps<{list?:Persons}>(),{
    list:() => [{id:'001',name:'小明',age:18}]
})

</script>

测试:

知识小结: 

  • 其中,我们可以在子组件使用  ? 来限制,是否为强制传递的值,使用代表不强制!!
  • 我们也可以指定默认值使用withDefaults宏函数指定默认值,
  • vue中我们使用宏函数时,可以不用手动导包
  • 当我们指定默认值时,一定要使用箭头函数,返回值的形式,如下;
  • //推荐指数:*****
    withDefaults(defineProps<{list?:Persons}>(),{
        list:() => [{id:'001',name:'小明',age:18}]
    })
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值