像专业人员一样验证你的Vue Props

开发 前端
随着你的应用程序规模的扩大,类型检查是防止错误的第一道防线。Vue的内置prop 验证是引人注目的。结合TypeScript,它可以让你对正确使用组件接口有很高的信心,减少bug,提高整体代码质量和开发体验。

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

让我们来探讨一下这个强大的工具,它可以帮助我们在开发和调试过程中减少错误并增加我们的信心。

一、基础知识

1.1 原始类型

验证原始类型就像为原始类型构造函数设置类型选项一样简单。

export default {
  props: {
    // Basic type check
    //  (`null` and `undefined` values will allow any type)
    propA: Number,
    // Multiple possible types
    propB: [String, Number],
    // Required string
    propC: {
      type: String,
      required: true
    },
    // Number with a default value
    propD: {
      type: Number,
      default: 100
    },
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

1.2 复杂类型

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

export default {
  props: {
    // 具有默认值的对象
    propE: {
      type: Object,
      // 对象或数组默认值必须从一个工厂函数。该函数接收原始组件作为参数接收的props。
      default(rawProps) {
        return { message: 'hello' }
      }
    },
    // 具有默认值的数组
    propF: {
      type: Array,
      default() {
        return []
      }
    },
    // 具有默认值的函数
    propG: {
      type: Function,
      // 与对象或数组默认不同,这不是工厂函数 - 这是一个用作默认值的函数
      default() {
        return 'Default function'
      }
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

类型可以是以下值之一:

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

另外,type 也可以是自定义类或者构造函数,断言会通过 instanceof 检查。例如,给定以下类:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

你可以像这样把它作为一个 props 类型。

export default {
  props: {
    author: Person
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

二、高级验证

2.1 验证器函数

props 支持使用一个验证器函数,这个函数接受 props 的原始值,并且必须返回一个布尔值来确定这个 props 是否有效。

// 自定义验证器函数
prop: {
  validator(value) {
    // 该值必须与这些字符串之一匹配
    return ['success', 'warning', 'danger'].includes(value)
  }
},
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

2.2 使用枚举

有时你想把数值缩小到一个特定的集合,这可以通过伪造这样的枚举来实现:

export const Position = Object.freeze({
  TOP: "top",
  RIGHT: "right",
  BOTTOM: "bottom",
  LEFT: "left"
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

可以在验证器中导入和使用,也可以作为默认值。

<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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

最后,父组件也可以导入和使用这个枚举,从而消除我们应用程序中魔术字符串的使用。

<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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

2.3 布尔型投射

布尔 prop 具有独特的行为,属性的存在与否可以决定prop值。

<!-- 相当于通过 :disabled="true" -->
<MyComponent disabled />

<!-- 相当于通过 :disabled="false" -->
<MyComponent />
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

三、TypeScript

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

3.1 Interfaces

我们可以使用一个接口和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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

3.2 真实枚举

我们已经探索了如何在 Javascript 中伪造枚举。这对于 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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

四、Vue 3

当使用带有 Options 或 Composition API 的 Vue 3 时,以上所有内容都有效。不同之处在于使用 <script setup> 时。必须使用 defineProps() 宏声明道具,如下所示:

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


<script setup>
// 还支持长语法
defineProps({
  title: String,
  likes: Number
})
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

或者当使用带有 <script setup> 的 TypeScript 时,可以使用纯类型注释来声明 props:

<script setup lang="ts">
defineProps<{
  title?: string
  likes?: number
}>()
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

或使用接口:

<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}
const props = defineProps<Props>()
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

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

<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}
// defineProps() 的反应性解构
// 默认值被编译为等效的运行时选项ime option
const { foo, bar = 100 } = defineProps<Props>()
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

结束

随着你的应用程序规模的扩大,类型检查是防止错误的第一道防线。Vue的内置prop 验证是引人注目的。结合TypeScript,它可以让你对正确使用组件接口有很高的信心,减少bug,提高整体代码质量和开发体验。

原文:https://fadamakis.medium.com/validating-your-vue-props-like-a-pro-5a2d0ed2b2d6作者:Fotis Adamakis

责任编辑:武晓燕
相关推荐

2021-12-14 19:40:07

Node路由Vue

2022-11-24 12:22:39

2017-11-06 14:18:03

2015-08-07 09:03:08

openSUSE软件

2021-09-26 13:51:50

混合ITNetOps网络

2018-05-17 15:43:40

IT

2023-04-05 14:19:07

FlinkRedisNoSQL

2024-10-09 14:48:34

2018-03-13 12:37:59

JavaHadoop大数据

2010-12-27 14:26:52

2016-11-03 10:03:49

云计算容器超融合

2020-03-08 11:31:15

渗透测试网络攻击安全工具

2022-01-10 21:00:12

LinuxGNOME截图工具

2013-12-31 09:19:23

Python调试

2013-12-17 09:02:03

Python调试

2023-05-23 13:59:41

RustPython程序

2022-12-21 15:56:23

代码文档工具

2023-05-29 08:49:04

ITCIO教学

2015-03-16 12:50:44

2021-05-20 08:37:32

multiprocesPython线程
点赞
收藏

51CTO技术栈公众号