vue props setup
时间: 2023-10-15 07:04:49 浏览: 40
在Vue3中,可以使用`setup`函数来接收父组件传递给子组件的数据(props)。 `setup`函数是组合式API的入口,它接受两个参数`props`和`context`。`props`是一个对象,包含了父组件传递给子组件的所有数据,在子组件中可以使用`props`进行接收。
如果你喜欢使用`setup`语法糖,可以使用`defineProps`来定义`props`。`defineProps`是一个编译器宏,无需引入。你可以在子组件中使用`defineProps`来定义需要的`props`,然后通过`toRefs`将`props`转换成响应式对象,以便在模板中使用。
下面是一个示例,展示了如何使用`setup`和`props`:
```vue
<script setup>
import { defineProps, toRefs } from 'vue'
const props = defineProps({
text: String,
message: Number
})
const { text } = toRefs(props)
const formatText = `Hi, ${text && text.value}`
</script>
<template>
<div>
{{ text }} <!-- 输出 hello world -->
{{ formatText }} <!-- 输出 Hi, hello world -->
{{ message }} <!-- 输出 233 -->
</div>
</template>
```
在这个例子中,我们使用`defineProps`定义了两个`props`:`text`和`message`。然后使用`toRefs`将`text`转换为响应式对象。最后,在模板中我们可以直接使用这些`props`的值。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>