如何使用设置脚本、打字稿和组合 API 在 vue 中使用验证器

2024-03-31

我有来自教程的以下代码示例,我尝试找出如何以与示例类似的方式使用验证器,使用脚本设置、打字稿和组合 API。

props: {
    image: {
      type: String,
      default: require("@/assets/default-poster.png"),
      validator: propValue => {
        const hasImagesDir = propValue.indexOf("@/assets/") > -1;
        const listOfAvailableExt = [".jpeg", ".jpg", ".png"];
        const isValidExt = listOfAvailableExt.some(ext =>
          propValue.endsWith(ext)
        );
        return hasImagesDir && isValidExt;
      }
    }
  }

我知道如何声明类型和默认值,但我找不到使用验证器的方法。有没有什么函数可以验证不同的属性?

interface Props {
  image: string
}

const props = withDefaults(defineProps<Props>(), {
  image: require("@/assets/default-poster.png")
});

In <script setup>, 只有函数参数 of defineProps()支持validator(自 Vue 3.2.31 起)。函数参数的类型与props option:

defineProps({
  image: {
    type: String,
    default: require("@/assets/default-poster.png"),
    validator: (propValue: string) => {
      const hasImagesDir = propValue.indexOf("@/assets/") > -1;
      const listOfAvailableExt = [".jpeg", ".jpg", ".png"];
      const isValidExt = listOfAvailableExt.some(ext =>
        propValue.endsWith(ext)
      );
      return hasImagesDir && isValidExt;
    }
  }
})

请注意,您不能将仅类型的 props 声明与函数参数混合defineProps(),因此任何其他道具也必须转换为选项形式。

或者,您可以实现自己的道具验证:

<script setup lang="ts">
interface Props {
  image: string
}

const props = withDefaults(defineProps<Props>(), {
  image: require("@/assets/default-poster.png")
});

if (import.meta.env.DEV /* process.env.NODE_ENV === 'development' */) {
  const isValidImage = (propValue: string) => {
    const hasImagesDir = propValue.indexOf("@/assets/") > -1;
    const listOfAvailableExt = [".jpeg", ".jpg", ".png"];
    const isValidExt = listOfAvailableExt.some(ext =>
      propValue.endsWith(ext)
    );
    return hasImagesDir && isValidExt;
  }

  if (!isValidImage(props.image)) {
    console.warn(`invalid image: ${props.image}`)
  }
}
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用设置脚本、打字稿和组合 API 在 vue 中使用验证器 的相关文章

随机推荐