【问题标题】:Vue3 prop String or PropTypeVue3 道具字符串或道具类型
【发布时间】:2021-07-27 17:47:19
【问题描述】:

我在 Vue3 项目中有一个组件,它接受一个可以是字符串或对象的道具。

所以是这样的:

import { defineComponent } from 'vue'

const Component = defineComponent({
  props: {
    book: {
      type: [String, Object]
    }
  }
})

但是,如果它是一个对象,我想添加一个像这样的类型(取自 vue3 文档):

import { defineComponent, PropType } from 'vue'

interface Book {
  title: string
  year?: number
}

const Component = defineComponent({
  props: {
    book: {
      type: Object as PropType<Book>
    }
  }
})

我的问题是,我怎样才能像这样将两者结合起来(这不起作用,因此我的问题):

import { defineComponent, PropType } from 'vue'

interface Book {
  title: string
  year?: number
}

const Component = defineComponent({
  props: {
    book: {
      type: [String, Object as PropType<Book>]
    }
  }
})

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

    为该道具类型使用函数表达式:

    const Component = defineComponent({
      props: {
        book: {           ?
          type: [String, () => Object as PropType<Book>]
        }
      },
      mounted() {
        const isBook = (obj: any): obj is Book => 'title' in obj // eslint-disable-line @typescript-eslint/no-explicit-any
    
        if (isBook(this.book)) {
          console.log(this.book.title)
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 2022-11-24
      • 2021-06-25
      • 2022-07-06
      • 1970-01-01
      • 2020-03-05
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多