prop父传子,setup方式
时间: 2023-10-11 09:08:17 浏览: 25
在 Vue.js 中,可以通过 `props` 来实现父组件向子组件传递数据。在子组件中,需要在 `props` 选项中声明接收哪些属性。而在 `setup` 函数中,可以通过 `props` 参数来访问父组件传递过来的属性。以下是一个简单的例子:
```html
<template>
<div>
<child-component :message="hello"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
hello: 'Hello World',
};
},
};
</script>
```
在子组件中,可以通过 `props` 参数来访问父组件传递过来的属性:
```html
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true,
},
},
setup(props) {
console.log(props.message); // 输出:Hello World
},
};
</script>
```
注意,在 `setup` 函数中访问 `props` 参数时,不能使用 `this` 关键字,而是直接使用函数参数中的 `props` 变量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)