vue3.2使用props传值的方法
dearweb
发布:2022-02-27 15:50:37阅读:
在vue3.x中,props是在setup外定义,以setup(props)的形式应用的,那么在vue3.2中该如何使用props呢?
在vue3.2中,提供了一个defineProps语法糖用于定义props,先上例子。
<script setup>
import { onMounted } from 'vue'
const props = defineProps({
customStr: {
type: String,
default: ''
},
customObj: {
type: Object,
default: () => {
return {}
}
}
})
onMounted(() => {
console.log(props.customObj)
})
</script>
<template>
{{ props.customStr }}
</template>从我上面的例子里可以看出,props需要用defineProps来定义,然后在使用时直接props.就可以使用了,那么还需要注意的点是:
defineProps可以不要import,但是eslint可能会检测到defineProps未定义,这种情况下可以直接import { defineProps } from 'vue'来解决
在模板中也需要用props.
例子中的写法是js的写法,对ts写法感兴趣的同学可以去看官方文档,这里也提供一个小例子
<script setup lang="ts">
const props = withDefaults(defineProps<{
customStr?: string
}>(), {
customStr: 'Hello World!'
});
</script>例子中的withDefaults是给变量赋初始值用的,在vue的官方文档中也有介绍。
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧