Vue 3 中 Props 传值的完整指南

您所在的位置:网站首页 vue3监听props传过来的值 Vue 3 中 Props 传值的完整指南

Vue 3 中 Props 传值的完整指南

2024-07-09 15:11| 来源: 网络整理| 查看: 265

一、定义 Props 类型

首先,我们需要定义一个接口来描述我们的props类型。这通常在一个专门的类型声明文件中完成,例如types/index.ts:

// types/index.ts export interface Parent { id: number; title: string; } export type ParentArray = Parent[]; 二、创建父组件

父组件负责定义数据和传递props给子组件。以下是父组件Parents.vue的示例:

import { ref } from 'vue'; import Children from './Children.vue'; import { ParentArray } from '../types'; const query = ref([ { id: 1, title: '文字1' }, { id: 2, title: '文字2' }, { id: 3, title: '文字3' } ]); 三、创建子组件

在子组件中,我们将演示三种不同的方法来接收父组件传递的 props。

1.只接收值 (defineProps)

在这种方法中,我们简单地接收并使用传递的值。

{{ item.title }} import { defineProps } from 'vue'; const propsA = defineProps(['query']); console.log('query 打印', propsA.query); 2. 接收并限制类型 (defineProps + 类型注释)

在这种方法中,我们通过定义类型来限制接收的 props。

{{ item.title }} import { defineProps } from 'vue'; import { Parent } from '../types'; const propsB = defineProps(); console.log('query 打印', propsB.query); 3. 接收、限制类型、设置默认值 (withDefaults)

在这种方法中,我们不仅限制类型,还设置默认值,以确保在没有传递 props 时组件能正常工作。

{{ item.title }} import { defineProps, withDefaults } from 'vue'; import { ParentArray } from '../types'; const propsC = withDefaults(defineProps(), { query: () => [{ id: 1, title: '古丽娜扎尔·拜合提亚尔' }] }); console.log('query 打印', propsC.query); 总结

在 Vue 3 中使用 TypeScript 定义和使用 Props。我们展示了三种方法来接收和处理父组件传递的数据:>

1.只接收值 (defineProps) 2.接收并限制类型 (defineProps + 类型注释) 3.接收、限制类型并设置默认值 (withDefaults)

这样,我们就创建了一个更加健壮和可维护的 Vue 3 组件系统。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3