在Vue中,我们可以通过组件间通信的方式,将数据从父组件传递给子组件,这个过程就是通过 props 实现的。
props 是一个数组,包含了需要从父组件传递给子组件的属性名称。例如,我们有一个 Child 组件,需要从父组件 Parent 中获取 message 属性,可以这样定义:
Vue.component('Child', {
props: ['message'],
template: '<div>{{ message }}</div>'
})
在父组件中使用 Child 组件,并传递 message 属性:
<Parent>
<Child :message="'Hello World!'"></Child>
</Parent>
注意,在父组件中传递属性时,需要使用 v-bind 或者简写 : 来绑定属性值。
此外,还可以在 props 中指定属性的类型、默认值等信息,例如:
Vue.component('Child', {
props: {
message: {
type: String,
default: 'Hello World!'
}
},
template: '<div>{{ message }}</div>'
})
在这个例子中,我们指定了 message 属性的类型为 String,默认值为 ‘Hello World!’。这样,在父组件中不传递 message 属性时,子组件就会使用默认值。