Skip to content

Vue3 在 setup 中对 props 进行参数校验【validator】 #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jtwang7 opened this issue Jul 14, 2022 · 0 comments
Open

Vue3 在 setup 中对 props 进行参数校验【validator】 #14

jtwang7 opened this issue Jul 14, 2022 · 0 comments

Comments

@jtwang7
Copy link
Owner

jtwang7 commented Jul 14, 2022

Vue3 在 setup 中对 props 进行参数校验【validator】

参考文章:

✅ 使用 defineProps API

<script lang="ts" setup>
  type Type = 'button' | 'submit' | 'reset';

  interface Props {
    type: Type;
  }

  const props = defineProps<Props>({ 
    type: {
      type: String,
      default: 'button',
      validator: (prop: Type) => ['button', 'submit', 'reset'].includes(prop)
    }
  });
</script>

WARNING
由于 TypeScript 中的设计限制,当它涉及到为了对函数表达式进行类型推理,你必须注意对象和数组的 validator 和 default 值:

import { defineComponent, PropType } from 'vue'

interface Book {
  title: string
  year?: number
}

const Component = defineComponent({
  props: {
    bookA: {
      type: Object as PropType<Book>,
      // 请务必使用箭头函数
      default: () => ({
        title: 'Arrow Function Expression'
      }),
      validator: (book: Book) => !!book.title
    },
    bookB: {
      type: Object as PropType<Book>,
      // 或者提供一个明确的 this 参数
      default(this: void) {
        return {
          title: 'Function Expression'
        }
      },
      validator(this: void, book: Book) {
        return !!book.title
      }
    }
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant