htmledit_views">子组件 (
父组件 (
子组件 (
父组件 (
1. 父组件向子组件传递数据的步骤
-
在子组件中定义
子组件通过props
:props
选项声明它期望接收的数据。props
可以是数组形式(简单声明)或对象形式(支持类型检查和默认值)。 -
在父组件中使用子组件时绑定
父组件通过props
:v-bind
(或简写为:
)将数据传递给子组件的props
。 -
子组件使用接收到的数据:
子组件可以直接在模板或逻辑中使用props
中的数据。
2. 示例代码
子组件 (ChildComponent.html" title=vue>vue
)
<template><div><h3>子组件</h3><p>接收到的消息:{{ message }}</p><p>接收到的数字:{{ number }}</p></div>
</template><script>
export default {// 定义 propsprops: {// 接收一个字符串类型的 messagemessage: {type: String,required: true, // 必传},// 接收一个数字类型的 number,默认值为 0number: {type: Number,default: 0, // 默认值},},
};
</script><style scoped>
div {border: 1px solid #ccc;padding: 10px;margin: 10px;
}
</style>
父组件 (ParentComponent.html" title=vue>vue
)
<template><div><h2>父组件</h2><input v-model="parentMessage" placeholder="输入消息" /><input v-model.number="parentNumber" placeholder="输入数字" /><button @click="sendData">传递数据</button><!-- 使用子组件并绑定 props --><ChildComponent :message="parentMessage" :number="parentNumber" /></div>
</template><script>
import ChildComponent from './ChildComponent.html" title=vue>vue';export default {components: {ChildComponent, // 注册子组件},data() {return {parentMessage: 'Hello from Parent', // 父组件的数据parentNumber: 42, // 父组件的数据};},methods: {sendData() {alert('数据已传递给子组件');},},
};
</script><style scoped>
div {padding: 10px;border: 1px solid #000;
}
</style>
3. 代码解析
子组件 (ChildComponent.html" title=vue>vue
)
-
props
定义:-
message
:接收一个字符串类型的数据,且是必传的(required: true
)。 -
number
:接收一个数字类型的数据,默认值为0
。
-
-
模板中使用
通过props
:{{ message }}
和{{ number }}
显示父组件传递过来的数据。
父组件 (ParentComponent.html" title=vue>vue
)
-
数据定义:
parentMessage
和parentNumber
是父组件的数据,通过v-model
绑定到输入框。 -
传递数据给子组件:
使用v-bind
(简写为:
)将父组件的数据绑定到子组件的props
:
<ChildComponent :message="parentMessage" :number="parentNumber" />
-
动态更新数据:
当用户在输入框中修改数据时,parentMessage
和parentNumber
会自动更新,并通过props
传递给子组件。
4. 运行效果
-
父组件显示两个输入框和一个按钮。
-
用户在输入框中输入内容,点击按钮后,数据会传递给子组件。
-
子组件实时显示父组件传递过来的数据。
5. 注意事项
-
props
是单向数据流:-
父组件向子组件传递数据是单向的,子组件不能直接修改
props
的值。 -
如果子组件需要修改数据,可以通过
$emit
触发事件,通知父组件修改。
-
-
可以通过props
验证:type
、required
、default
等选项对props
进行验证,确保数据的正确性。 -
动态
使用props
:v-bind
动态绑定props
,可以实现父组件数据变化时,子组件自动更新。