Vue3 props的使用详解

"本文介绍了Vue.js中定义和使用Props的各种方法,包括字符串数组声明、对象实现、类型标注以及camelCase命名。通过示例展示了如何在模板中直接使用Props,并提到了动态绑定Props以实现数据的动态传递。同时,强调了在最新的Vue版本中,`defineProps`已不再需要额外引入,并且推荐使用`<script setup lang="ts">`语法糖。"

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

Props 声明

1、字符串数组声明props

<script setup lang="ts">
const props = defineProps(["cat"])
 
console.log(props.cat)
</script>

 2.对象实现props

<script setup lang="ts">
const props = defineProps({
    cat:string
})
</script>

//可以在模板中直接使用cat变量
<template>
  {{ cat }}
</template>

你还可以使用类型标注,这是ts的特性。

<script setup lang="ts">
const props = defineProps<{
    cat?:string
}>()
</script>

//或者使用接口

interface animal{
    cat?:string
}

const props = defineProps<animal>()

3、使用camelCase(小驼峰命名法),可以在模板中直接使用(如第一个例子)。看代码

defineProps({
  getSex: String
})


<template>
 {{getSex}}
</template>

4、动态绑定props

import {reactive} from "vue"

const data=reactive({
    article:{
        cat:"tom"
}
})

//下方传递这个cat

<span :animal='data.article.cat'></span>

//然后你就可以改变cat的属性值就可以实现动态传递数据了

注意事项:defineprops在之前的Vue版本中需要引入,但是现在是不需要了。上面几个例子是建立在setup语法糖的基础上编写的即<script setup lang="ts">,如果你不是太熟悉setup语法糖,那么就需要在script标签中使用setup(){}中使用props属性取得传递的数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值