vue 父传子
时间: 2023-06-29 19:20:25 浏览: 50
Vue 中父组件向子组件传递数据可以通过 props 进行实现。props 是父组件传递到子组件的数据,子组件通过 props 接收数据。以下是一个简单的示例:
父组件:
```html
<template>
<div>
<child-component :message="message"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello from parent component!'
}
}
}
</script>
```
子组件:
```html
<template>
<div>
{{ message }}
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
}
</script>
```
在父组件中,我们通过在子组件上使用 `:message="message"` 的方式将 `message` 数据传递到子组件。在子组件中,我们使用 `props` 定义了一个 `message` 属性,并指定它的类型为 `String`,并设置了 `required: true`,表示这个属性是必需的。子组件中可以通过 `this.message` 访问到父组件传递过来的数据。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)