vue父组件向子组件传递数据?
时间: 2023-08-25 20:07:55 浏览: 109
在 Vue.js 中,我们可以通过 props 将数据从父组件传递给子组件。
在组件中,我们可以声明一个属性并将它绑定到子组件上。例如:
<template>
<div>
<child-component :message="hello"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
hello: 'Hello from parent component!'
}
}
}
</script>
在子组件中,我们可以通过 props 属性来接收来自父组件的数据。例如:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
在上面的示例中,我们声明了一个名为 message
的 props,它的类型为 String
。在子组件中,我们可以通过 this.message
来访问它。
当然,你也可以在子组件中使用 v-bind
来动态地绑定 props。例如:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
在父组件中,我们可以这样使用:
<template>
<div>
<child-component v-bind:message="hello"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
hello: 'Hello from parent component!'
}
}
}
</script>
在上面的示例中,我们使用 v-bind
来动态地绑定 hello
变量到 message
props 上。
相关推荐











