vue父传子代码详情 和代码中文详细注解
时间: 2024-04-12 09:26:50 浏览: 12
当在Vue中需要将数据从父组件传递给子组件时,可以使用props属性。下面是一个示例代码,包含了中文详细注解:
父组件(Parent.vue):
```vue
<template>
<div>
<Child :message="message" /> <!-- 将父组件的message属性传递给子组件 -->
</div>
</template>
<script>
import Child from './Child.vue'; // 导入子组件
export default {
components: {
Child, // 注册子组件
},
data() {
return {
message: 'Hello from parent!', // 定义父组件的message属性
};
},
};
</script>
```
子组件(Child.vue):
```vue
<template>
<div>
<p>{{ message }}</p> <!-- 使用props属性接收父组件传递的message属性 -->
</div>
</template>
<script>
export default {
props: ['message'], // 声明props属性,指定要接收的属性名
};
</script>
```
在父组件中,通过在子组件标签上使用`:`绑定语法,将父组件的`message`属性传递给子组件。在子组件中,使用`props`属性声明接收的属性名,然后可以在模板中使用该属性。
以上代码示例演示了如何在Vue中实现父组件向子组件传递数据,并通过props属性来接收和使用传递的数据。