likes
comments
collection
share

02. 将参数 props 限制在一个类型的列表中

作者站长头像
站长
· 阅读数 15

这节课,我们来看下,怎样将一个 props 限制在一个特定值的集合中。

现在我们有一个 Image 组件,内容如下:

<template>
  <img
    class="image"
    :class="computeImgStyle"
    src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic3.zhimg.com%2Fv2-9cd5b6a8a9a4882925a3fbb7d724c610_1200x500.jpg&refer=http%3A%2F%2Fpic3.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1671460510&t=1439c0f17c7afc467b9798f0466cdbda"
    alt="图片加载失败"
  />
</template>

<script setup lang="ts">
  const props = defineProps({
    imgStyle: {
      type: String,
      default: 'square'
    }
  });
  const computeImgStyle = computed(() => {
    return {
      square: props.imgStyle === 'square',
      rounded: props.imgStyle === 'rounded'
    };
  });
</script>

<style scoped lang="scss">
  .image {
    margin: 100px;
    width: 70%;
  }
  .square {
    border-radius: 0;
  }
  .rounded {
    border-radius: 20px;
  }
</style>

Image 组件接受一个 imgStyle 参数,然后,我们利用计算属性根据传入的 imgStyle 参数给组件里的图片添加圆角圆角样式,缺省值是没有圆角属性,当传入的值为 rounded ,就给图片添加一个 20px 的圆角,在父组件中这样引入:

<template>
  <Image imgStyle="square" />
</template>

<script setup lang="ts">
  import Image from 'Components/Image.vue';
</script>

<style scoped></style>

运行:

02. 将参数 props 限制在一个类型的列表中

这会有一个小问题,当用户传入非 squarerounded 的时候,图片的圆角是没有变化的,或者对应的单词拼写错误,也是没有效果。如果用户以为此时传入的值是对的,就会有疑问,咋没有效果呢?控制台也没有报错,这样还需要时间去排查错误。

所以,当用户传入是错误的值时,我们封装的组件能够给出提示就很有必要了,\那怎么判断用户传入的值是否在我们的约定中呢?

这时,就可以借助 validator 属性,改写下 Image 的代码,如下:

const props = defineProps({
    imgStyle: {
      type: String,
      default: 'square',
      validator: (value: any) => {
        return ['square', 'rounded'].includes(value);
      }
    }
  });

validator 属性接受一个参数,这个参数就是我们从父组件传进来的值,这里使用 includes 来判断,传入进来的值是否在我们的数组内,如果是则返回 true ,否则返回 false ,此时控制台就会给出警告。

比如在父组件中,随便传入一个值:

<template>
  <Image imgStyle="123123" />
</template>

在控制台可以看见此警告: 02. 将参数 props 限制在一个类型的列表中

有了警告,用户就能快速定义到问题所在了。

validator 的验证,如果翻看 elementUI 或 Antd UI库,如 Button组件,它有几种类型像 success、info、danger等等。它里面也有用到 validator 的验证器,所以想要封装更好的组件,这个 validator 是必不可少的。