企业项目管理、ORK、研发管理与敏捷开发工具平台

网站首页 > 精选文章 正文

Vue3 中通过 props 属性实现父组件向子组件传递值

wudianyun 2025-06-13 17:21:36 精选文章 2 ℃

在 Vue3 中,可以通过 props 属性实现父组件向子组件传递值。以下是一个完整的示例代码:

<template>

<div>

<h2>父组件</h2>

<p>父组件的值:{{ parentValue }}</p>

<ChildComponent:childValue="parentValue" />

</div>

</template>

<script>

import { defineComponent } from 'vue';

import ChildComponent from './ChildComponent.vue';

export default defineComponent({

name: 'ParentComponent',

components: {

ChildComponent,

},

data() {

return {

parentValue: '父组件的值',

};

},

});

</script>

在上述代码中,父组件通过定义一个 data 属性parentValue 来存储要传递给子组件的值。然后,在父组件的模板中,使用 ChildComponent 标签,并通过:绑定属性的方式将 parentValue 传递给子组件的 childValue 属性。

接下来,我们需要创建子组件 ChildComponent,并在子组件中接收父组件传递的值:

<template>

<div>

<h2>子组件</h2>

<p>子组件接收到的值:{{ childValue }}</p>

</div>

</template>

<script>

import { defineComponent, PropType } from 'vue';

export default defineComponent({

name: 'ChildComponent',

props: {

childValue: {

type: String as PropType<string>,

required: true,

},

},

});

</script>

在子组件的 props 属性中,定义了一个名为childValue 的属性,类型为字符串,并设置为必需的。这样,子组件就可以接收到父组件传递的值,并在模板中使用 childValue 来显示。

通过以上代码,就实现了父组件向子组件传递值的功能。

Tags:

最近发表
标签列表