父向子组件传递数据

  在父组件中使用v-bind,可以为子组件动态绑定props,任意类型的值都可以出传递给子组件的props,包括字符串,数字,布尔值,数组,对象等

1
1.字符串
接下来以父组件传递字符串的类型props数据,代码如下:

<template>
<Child:init="username"/>
</teplate>
<script setup>
import{ref}from'Vue'
const username =ref('小圆')
</script>

init属性是子组件声明的props,通过v-bind绑定init属性。上述代码,用到了名称为Child子组件,该子组件代码如下:


<template></template>
<script setup>
const porps = defineProps(['init'])
console.log(props)
</script>

上述代码用于接收到的props数据输出到控制台,读者可以自行查看控制台的输出结果。

2.数字
从父组件为子组件传递数字类型props数据,代码如下:

<template>
<Child:init="12"/>
<Child:init="age"/>
</template>
<script setup>
import Child from 'vue'
const age = ref(12)
</script>

上述代码中,init属性是子组件声明的props,通过v-bind实现将12识别为表达式而不是字符串,init属于动态赋值。

3.布尔值
从父组件为子组件传递布尔类型props数据,代码如下:

<template>
<Child:init/>
<Child:init="flase"/>
<Child:init="is Flag"/>
</template>
<script setup>
import Child from './Child.vue'
const isFlag = ref(true)
</script>

上述代码中,init属性是子组件声明的props,通过v-bind实现将flase识别为表达式而不是字符串,通过isFlag属性进行动态赋值。

4.数组
从父组件中为子组件传递数组类型的props数据。

<template>
<Child :init="['唱歌','跳舞','滑冰']"/>
<Child :init="hobby"/>
</template>
<script set up>
import Child from'./Child.vue'
import {ref}from'vue'
const hobby = ref(['唱歌','跳舞','滑冰'])
</script>

init属性是子组件声明的【props】,第二行代码通过v-bind实现将数组识别为表达式而不是字符串,第三行代码表示为init属性进行动态赋值。

5.对象
从父组件中为子组件传入对象类型的props数据,或者将对象中的部分属性作为被传入的props数据

<template>
<Child :init="{height:'180厘米',weight:'70千克'}"/>
<Child :height="bodyInfo.height":weight='bodyInfo.weight"/>
<Child v-bind="bodyInfo"/>
</template>
<script setup>
import Child from'./Child.vue'
import {reactive} from 'vue'
const bodyInfo = reactive({
height:'180厘米',
weight:'70千克',
})
</script>

上述代码中,init,height,weight,属性是子组件中声明的props,需要在子组件中自行添加height,weight这两个props,第二行代码用于通过v-bind实现将对象识别为表达式而不是字符串,第三行代码表示通过bodyInfo.height,bodyInfo.weight进行动态赋值。第4行代码表示将一个对象的所有属性都作为prop传入,该语法可以取代v-bind:prop-name形式语法,第4行行代码相当于第3行代码简化版,9~12行代码定义了bodyInfo对象,表示身体信息,包括身高height和体重weight。\

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值