Vue2 vs Vue3 的 props 对比

🌟 Vue2 vs Vue3 的 props 对比 🌟

在 Vue2 和 Vue3 中,props 的使用方式有一些变化,尤其是在 TypeScript 支持和语法上。以下是详细的对比和 withDefaults 的用法说明!


1. Vue2 的 props

在 Vue2 中,props 是通过 props 选项定义的,支持数组或对象形式。

示例:

javascript 复制代码
export default {
  props: {
    // 基础类型检测
    title: String,
    // 多个可能的类型
    likes: [String, Number],
    // 必填项
    isPublished: {
      type: Boolean,
      required: true
    },
    // 默认值
    commentIds: {
      type: Array,
      default: () => [1, 2, 3]
    }
  }
};

特点:

  • 不支持 TypeScript 类型推断。
  • 默认值和类型验证需要通过对象形式定义。

2. Vue3 的 props

在 Vue3 中,props 可以通过 defineProps 函数定义,支持 TypeScript 类型推断。

示例:

xml 复制代码
<script setup lang="ts">
const props = defineProps({
  title: String,
  likes: [String, Number],
  isPublished: {
    type: Boolean,
    required: true
  },
  commentIds: {
    type: Array,
    default: () => [1, 2, 3]
  }
});
</script>

使用 TypeScript 的泛型定义:

ini 复制代码
<script setup lang="ts">
interface Props {
  title: string;
  likes?: string | number;
  isPublished: boolean;
  commentIds?: number[];
}

const props = defineProps<Props>();
</script>

特点:

  • 支持 TypeScript 类型推断。
  • 语法更简洁,适合组合式 API。

3. withDefaults的用法

在 Vue3 中,使用 TypeScript 的泛型定义 props 时,如果需要设置默认值,可以使用 withDefaults 函数。

示例:

ini 复制代码
<script setup lang="ts">
interface Props {
  title: string;
  likes?: string | number;
  isPublished: boolean;
  commentIds?: number[];
}

const props = withDefaults(defineProps<Props>(), {
  title: "Default Title",
  likes: 0,
  isPublished: false,
  commentIds: () => [1, 2, 3]
});
</script>

说明:

  • withDefaults 的第一个参数是 defineProps 的返回值。
  • 第二个参数是一个对象,用于设置默认值。

📊 Vue2 和 Vue3 的 props 对比表

特性 Vue2 Vue3
定义方式 props选项 defineProps函数
TypeScript 支持 不支持 支持
默认值设置 通过 default属性 通过 withDefaults函数
类型验证 通过 type属性 通过 TypeScript 类型或 type属性
语法简洁性 较繁琐 更简洁

🌈 总结

  • Vue2 :使用 props 选项定义,不支持 TypeScript 类型推断。
  • Vue3 :使用 defineProps 定义,支持 TypeScript 类型推断,语法更简洁。
  • withDefaults:用于在 TypeScript 中为 props 设置默认值。

Vue3 的 props 设计更加现代化,尤其是对 TypeScript 的支持非常友好!快来试试吧!🚀

相关推荐
雪芽蓝域zzs36 分钟前
第24章:ECharts 地图组件(基础行政区地图,若依 Vue3)
vue.js·echars
CoderYanger39 分钟前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
爱学习的执念1 小时前
助力金九银十1000道软件测试面试题(功能、接口、自动化、WEB、APP.......)附答案
软件测试·面试
计算机毕设定制辅导-无忧学长2 小时前
《基于Vue的流浪动物救助中心管理系统的设计与实现》
java·vue.js·spring boot·流浪动物救助中心管理系统
小的~~2 小时前
银河麒麟V10 ARM部署TDengine(涛思)工业时序数据库安装与测试
面试·程序员创富
雪芽蓝域zzs2 小时前
第25章:地图下钻交互(点击省份,切换到对应省份城市地图)
vue.js·echars
daols882 小时前
vue 甘特图组件 vxe-gantt 自动计算工期显示关键路径
vue.js·vxe-gantt
—Qeyser3 小时前
Element Plus 安装与配置指南 (Vue 3 + Vite + TS)
vue.js
雪芽蓝域zzs3 小时前
第19章:ECharts 组合图(折线 + 柱状混合图,双 Y 轴)
vue.js·echars
小刘在重生~3 小时前
Oracle_day2 单行函数|组函数|分组|伪列|子查询|分页|多表连接
笔记·oracle·面试