<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src
import Ajv, { JSONSchemaType, DefinedError } from 'ajv'
import ajvErrors from 'ajv-errors'
export default defineComponent({
components: {
HelloWorld
},
setup: function () {
const ajv = new Ajv({ allErrors: true })
ajvErrors(ajv)
interface Foo {
foo?: {
id: 1 | 2 ;
};
}
type MyData = Foo;
type JSONSchemaMyType = JSONSchemaType<Required<MyData>>; // 需要先转换为必须元素
const schema: JSONSchemaMyType = {
type: 'object',
properties: {
foo: {
type: 'object',
properties: {
id: {
type: 'number',
enum: [1, 2],
errorMessage: {
type: 'id数据类型错误'
}
}
},
required: ['id'],
errorMessage: {
type: 'foo数据格式错误',
required: {
id: 'id参数缺失'
}
}
}
},
additionalProperties: false,
required: ['foo']
}
const validate = ajv.compile(schema)
const data: any = {
foo: {}
}
if (validate(data)) {
// data is MyData here
console.log(data.foo)
} else {
console.log(validate.errors)
// The type cast is needed to allow user-defined keywords and errors
// You can extend this type to include your error types as needed.
for (const err of validate.errors as DefinedError[]) {
switch (err.keyword) {
case 'minimum':
// err type is narrowed here to have "minimum" error params properties
break
}
}
}
}
})
</script>
网友评论