rgu*_*utt 2 typescript vue.js vue-validator vue-composition-api vue-script-setup
我有来自教程的以下代码示例,我尝试找出如何以与示例类似的方式使用验证器,使用脚本设置、打字稿和组合 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道如何声明类型和默认值,但我找不到使用验证器的方法。有没有什么函数可以验证不同的属性?
interface Props {
image: string
}
const props = withDefaults(defineProps<Props>(), {
image: require("@/assets/default-poster.png")
});
Run Code Online (Sandbox Code Playgroud)
在 中<script setup>,仅支持的函数参数(从 Vue 3.2.31 开始)。函数参数与选项具有相同的类型:defineProps()validatorprops
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;
}
}
})
Run Code Online (Sandbox Code Playgroud)
请注意,您不能将仅类型的 props 声明与 的函数参数混合defineProps(),因此任何其他 props 也必须转换为选项形式。
或者,您可以实现自己的道具验证:
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3040 次 |
| 最近记录: |