programing

Vue prop 유형 유효성 검사 개체 스키마

bestcode 2022. 7. 16. 15:11
반응형

Vue prop 유형 유효성 검사 개체 스키마

반응에서 소품이 객체임을 정의한 다음 해당 객체의 특성 유형(예: 모양)을 정의할 수 있습니다.Vue에서는 validator 기능을 사용하여 객체가 특정 형상의 것인지 확인할 수 있는 유일한 방법인 것 같습니다.그것이 현재 권장되는 전략입니까?검증에 사용할 수 있는 다른 라이브러리가 있다고 생각합니다만, Vue가 처리할 수 있을 것 같습니다.

반드시 TypeScript를 사용해야 합니다.예상하는 내용을 "유형 주석"이라고 합니다. TypeScript 빠른 시작 튜토리얼에 대한 간략한 개요를 볼 수 있습니다.

Vue.js는 TypeScript를 즉시 지원합니다.https://vuejs.org/v2/guide/typescript.html 를 참조해 주세요.

@Clorichel의 답변을 참고하겠습니다.TypeScript는 저에게 놀라운 결과를 가져다 주기 때문입니다.답변이 늦었지만 당신과 같은 것이 필요했습니다. "이 소품은 문자열입니까, 숫자입니까?"가 아니라 오브젝트 스키마 검증입니다.TypeScript는 계약상 오브젝트의 형상을 그 타입(인터페이스)으로 제한하는 인터페이스를 제공합니다.그래서 만약에 내가

interface GreetingSchema {
  message: string;
}

하고있다let myGreeting = <GreetingSchema>{ message: 1234 }에러가 발생합니다.

Type '{ message: number; }' cannot be converted to type 'GreetingSchema'.
  Types of property 'message' are incompatible.
    Type 'number' is not comparable to type 'string'.

Vue와 통합하여 이 기능을 좀 더 확장하기 위해 컴파일 시간 동안 인터페이스를 활용하여 부모에서 자녀로 전달되는 컴포넌트 소품에서 객체 스키마 검증을 수행할 수 있습니다.예를 들어, 한 아이가Greeting컴포넌트(Greeting.vue)는 전달되는 소품 오브젝트 스키마와 결합할 수 있습니다(네스트된 스키마를 사용하여 매끄럽게 합니다).

<template>
  <div>
    {{message}}{{
      speaker
        ? ` from ${speaker.firstName}${
            speaker.lastName ? ` ${speaker.lastName}` : ''
          }
        : ''
    }}
  </div>
</template>

<script lang="ts">
export default {
  name: 'greeting',
  props: ['message', 'speaker'],
}

interface SpeakerSchema { // this will be a nested schema
  firstName: string;
  lastName?: string; // last name of speaker is optional
}

export interface GreetingSchema {
  message: string;
  speaker?: SpeakerSchema; // speaker is optional
}
</script>

그 후, 다음의 파일을 Import 할 수 있습니다.Greeting성분과 그에 대응하는 성분GreetingSchema부모에게 전달하여 부모가 자신의 부모에게 전달될 때마다greetingData어린애까지Greeting와 함께v-bind,greetingData에 정의되어 있는 형상에 의해 구속됩니다.GreetingSchema

<template>
  <div>
    This greeting is being displayed from the parent:
    <greeting v-bind="greetingData" /> 
  </div>
</template>

<script lang="ts">
import Greeting, {GreetingSchema} from './Greeting' // path to Greeting.vue

export default {
  name: 'parent',
  components: {Greeting},
  data () {
    return {
      greetingData: <GreetingSchema>{
        message: 'hi there',
        speaker: {
          firstName: 'myFirstName',
          lastName: 1234 // error because it's not a string
        },
      }
    }
  },
}
</script>

놀라운 점은 에러가 텍스트에디터에 적절한 확장자를 붙여 직접 표시할 수 있다는 것입니다..vue파일입니다. Visual Studio Code를 사용하고 있습니다.Vetur 확장자는 TypeScript를 즉시 지원합니다.더욱 놀라운 것은 TypeScript 홈페이지에는 Vue의 단일 파일 컴포넌트에서 TypeScript를 사용하는 프레젠테이션이 있다는 입니다.

TypeScript 전용 솔루션의 문제는 컴파일 시에만 유형을 검사하고 유형 검사로 제한된다는 것입니다.동적 개체를 전달하거나 추가 데이터 제약이 필요한 경우 런타임에 이 방법을 사용하면 도움이 되지 않습니다.

최근에 런타임 검증을 위한 라이브러리를 찾았지만, 자바스크립트 예약어를 함수 이름으로 사용했기 때문에 Vue 2.x나 Babel 컴파일러에서 사용하기에는 적합하지 않았습니다. 프로젝트를 TypeScript JavaScript를 하였습니다.asSuccess()VueJs の v v v v v 。

예를 들어 다음과 같은 TypeScript 인터페이스가 있는 경우...

interface Pet {
  name: string;
  species: string;
  age?: number;
  isCute?: boolean;
}

다음과 같은 JavaScript 또는 TypeScript 코드를 사용하여 Pet 속성을 검증할 수 있습니다.

import { tObject, tString, tNumber, tBoolean, optional } from 'runtime-validator'

// VueJs component
export default {
  name: 'MyPet',
  props: {
    pet: {
      type: Object,
      required: true,
      validator: tObject({
        name: tString(),
        species: tString(),
        age: optional(tNumber()),
        isCute: optional(tBoolean())
      }).asSuccess
    }
  },
  ...
}

tObject()는 정의된 필드에 추가 필드가 있는 개체를 받아들입니다.필드를 하지 않을 를 사용합니다.tObjectStrict().

값 제약 조건을 추가할 수도 있습니다.

export default {
  name: 'MyPet',
  props: {
    pet: {
      type: Object,
      required: true,
      validator: tObject({
        name: tString(),
        species: oneOf("cat", "dog", "bird"),
        age: optional(range(0, 150)),
        isCute: optional(tBoolean())
      }).asSuccess
    }
  },
  ...
}

유닛 테스트, vuex 액션 및 돌연변이, 서버 측 페이로드 등의 데이터 검증에도 사용할 수 있기 때문에 속성보다 훨씬 광범위한 응용 프로그램을 제공합니다.

자세한 내용은 여기를 참조하십시오.

언급URL : https://stackoverflow.com/questions/41987772/vue-prop-type-validation-object-schema

반응형