Vue3 props的写法和vue2差别还是比较大的,它基于defineProps进行定义,详细用法如下:
Props 声明
1、字符串数组声明props
<script setup> const props = defineProps(["cat"]) console.log(props.cat) </script>
2.对象实现props
<script setup>
const props = defineProps({
cat:string
})
</script>
//可以在模板中直接使用cat变量
<template>
{{ cat }}
</template>你还可以使用类型标注,这是ts的特性。
<script setup>
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> ,如果你不是太熟悉setup语法糖,那么就需要在script标签中使用 setup(){} 中使用props属性取得传递的数据
本文为CSDN博主「一沓纸稿」的原创文章,原文链接:https://blog.csdn.net/qq_45662523/article/details/126671079
