首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >验证 Vue Props 类型,你这几种方式你可能还没试用过!

验证 Vue Props 类型,你这几种方式你可能还没试用过!

作者头像
前端小智@大迁世界
发布2022-09-27 17:05:47
1.3K0
发布2022-09-27 17:05:47
举报

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

vue 要求任何传递给组件的数据,都要声明为 props。此外,它还提供了一个强大的内置机制来验证这些数据。这就像组件和消费者之间的契约一样,确保组件按预期使用。

这节课我们来看下这个验证机制,它可以帮助我们在开发和调试过程中减少 but,增加我们的自信心(摸鱼时间)。

基础

原始类型

验证基本类型比较简单,这里我们不过多的介绍,直接看下面例子:

export default {
  props: {
    // Basic type check
    //  ("null "和 "undefined "值允许任何类型)
    propA: Number,
    // 多种可能的类型
    propB: [String, Number],
    // 必传的参数
    propC: {
      type: String,
      required: true
    },
    // 默认值
    propD: {
      type: Number,
      default: 100
    },
  }
}
复杂类型

复杂类型也可以用同样的方式进行验证。

export default {
  props: {
    // 默认值的对象
    propE: {
      type: Object,
      // 对象或数组的默认值必须从
      // 一个工厂函数返回。该函数接收原始
      // 元素作为参数。
      default(rawProps) {
        return { message: 'hello' }
      }
    },
    // 数组默认值
    propF: {
      type: Array,
      default() {
        return []
      }
    },
    // 函数默认值
    propG: {
      type: Function,
       // 不像对象或数组的默认值。
      // 这不是一个工厂函数 
      // - 这是一个作为默认值的函数
      default() {
        return 'Default function'
      }
    }
  }
}

type 可以是以下之一:

  • Number
  • String
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

此外,type 也可以是一个自定义的类或构造函数,然后使用 instanceof 进行检查。例如,给定下面的类:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
}

我们可以把 Person 作为一个类型传递给 prop 类型:

export default {
  props: {
    author: Person
  }
}

高级验证

validator 方法

Props 支持使用一个 validator 函数。这个函数接受 prop 原始值,并且必须返回一个布尔值来确定这个 prop 是否有效。

   prop: {
      validator(value) {
        // The value must match one of these strings
        return ['success', 'warning', 'danger'].includes(value)
      }
    }
使用枚举

有时我们想把值缩小到一个特定的集合,这可以通过枚举来实现:

export const Position = Object.freeze({
  TOP: "top",
  RIGHT: "right",
  BOTTOM: "bottom",
  LEFT: "left"
});

它可以导入 validator 中使用,也可以作为默认值:

<template>
  <span :class="`arrow-position--${position}`">
    {{ position }}
  </span>
</template>

<script>
import { Position } from "./types";
export default {
  props: {
    position: {
      validator(value) {
        return Object.values(Position).includes(value);
      },
      default: Position.BOTTOM,
    },
  },
};
</script>

最后,父级组件也可以导入并使用这个枚举,它消除了我们应用程序中对魔法字符串的使用:

<template>
  <DropDownComponent :position="Position.BOTTOM" />
</template>

<script>
import DropDownComponent from "./components/DropDownComponent.vue";
import { Position } from "./components/types";
export default {
  components: {
    DropDownComponent,
  },
  data() {
    return {
      Position,
    };
  },
};
</script>

布尔映射

布尔类有独特的行为。属性的存在或不存在可以决定 prop 的值。

<!-- 等价于 :disabled="true" -->
<MyComponent disabled />

<!-- 价于 :disabled="false" -->
<MyComponent />

TypeScript

将Vue的内置 prop 验证与 TypeScript相结合,可以让我们对这一机制有更多的控制,因为TypeScript原生支持接口和枚举。

Interface

我们可以使用一个接口和 PropType 来注解复杂的 prop 类型。这确保了传递的对象将有一个特定的结构。

<script lang="ts">
import Vue, { PropType } from 'vue'
interface Book {
  title: string
  author: string
  year: number
}
const Component = Vue.extend({
  props: {
    book: {
      type: Object as PropType<Book>,
      required: true,
      validator (book: Book) {
        return !!book.title;
      }
    }
  }
})
</script>
枚举

我们已经探讨了如何在 JS 中伪造一个枚举。这对于TypeScript来说是不需要的,它本向就支持了:

<script lang="ts">
import Vue, { PropType } from 'vue'
enum Position {
  TOP = 'top',
  RIGHT = 'right',
  BOTTOM = 'bottom',
  LEFT = 'left',
}
export default {
  props: {
    position: {
      type: String as PropType<Position>,
      default: Position.BOTTOM,
    },
  },
};
</script>

Vue 3

上述所有内容在使用 Vue 3与 选项API 或 组合API 时都有效。区别在于使用 <script setup>时。props 必须使用 defineProps() 宏来声明,如下所示:

<script setup>
const props = defineProps(['foo'])
console.log(props.foo)
</script>


<script setup>
defineProps({
  title: String,
  likes: Number
})
</script>

或者在使用 TypeScript 的 <script setup> 时,可以使用纯类型注解来声明 prop:

<script setup lang="ts">
defineProps<{
  title?: string
  likes?: number
}>()
</script>

或者使用一个接口:

<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}
const props = defineProps<Props>()
</script>

最后,在使用基于类型的声明时,声明默认值。

<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}


const { foo, bar = 100 } = defineProps<Props>()
</script>

代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

总结


作者:Fotis Adamakis 译者:前端小智 来源:mediun

原文:https://fadamakis.mdium.com/v... 本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-08-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基础
    • 原始类型
      • 复杂类型
      • 高级验证
        • validator 方法
          • 使用枚举
          • 布尔映射
          • TypeScript
            • Interface
              • 枚举
              • Vue 3
              • 总结
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档