在Vue 3中,父组件向子组件传递数据(也称为"props")是一个非常常见的模式。这是通过props选项在子组件中定义的,然后在父组件的模板中使用该子组件时通过属性(attributes)传递数据。
步骤 1: 定义子组件的props
首先,在子组件中定义你希望从父组件接收的props。
vue复制代码
|---|-----------------------------------------------------------|
| | <!-- ChildComponent.vue --> |
| | <template> |
| | <div> |
| | <p>来自父组件的消息: {``{ message }}</p> |
| | </div> |
| | </template> |
| | |
| | <script> |
| | export default { |
| | name: 'ChildComponent', |
| | props: { |
| | message: String // 定义了一个名为 `message` 的prop,类型为String |
| | } |
| | } |
| | </script> |
步骤 2: 在父组件中使用子组件并传递数据
然后,在父组件的模板中,你可以使用这个子组件,并通过属性传递数据给它。
vue复制代码
|---|-------------------------------------------------------|
| | <!-- ParentComponent.vue --> |
| | <template> |
| | <div> |
| | <ChildComponent :message="parentMessage" /> |
| | </div> |
| | </template> |
| | |
| | <script> |
| | import ChildComponent from './ChildComponent.vue'; |
| | |
| | export default { |
| | components: { |
| | ChildComponent |
| | }, |
| | data() { |
| | return { |
| | parentMessage: 'Hello from Parent!' |
| | } |
| | } |
| | } |
| | </script> |
注意,在父组件中传递props时,我们使用v-bind指令(简写为:)来绑定数据到子组件的属性上。在这个例子中,parentMessage数据属性被绑定到了ChildComponent的message属性上。
总结
- 子组件 定义它想要接收的
props。 - 父组件 通过子组件的标签属性传递数据,并使用
v-bind或简写:来绑定这些值。
Vue的props系统允许组件之间进行清晰的通信,同时保持了组件的独立性和可重用性。通过props,父组件可以安全地传递数据到子组件,而不需要担心子组件会意外修改这些数据(除非使用了.sync修饰符或v-model,但它们在Vue 3中有不同的用法和限制)。