【问题标题】:VueJs how to set prop type to any?VueJs如何将道具类型设置为任何?
【发布时间】:2019-01-27 10:29:39
【问题描述】:

我有定义类型的道具,但我希望它们中的最后一个接受任何类型的值

props: {
        Size: String,
        Label: String,
        Name: String,
        value: Any
    }

我能做到这一点吗?

【问题讨论】:

  • 将其设置为null 以匹配任何类型。

标签: vue.js


【解决方案1】:

来自VueJS docs

nullundefined 值将通过任何类型验证

或者您可以使用数组并将所有需要的类型放入其中:

propB: [String, Number]

【讨论】:

  • nullundefined 将通过任何类型验证 - 只需确保 required 设置为 trueFound it here.
【解决方案2】:

当你有定义类型的道具时支持道具类型any

props: {
    custom1: null, // set as `null`
    custom2: undefined,  // or `undefined`
       
    // if you need to add extra rules, simply don't set the `type` prop
    custom3: {
        required: true,
        //... rest of your props
    }
}

演示:https://jsfiddle.net/xa91zoyq/4/

【讨论】:

    【解决方案3】:

    这是我为通过 lint 验证所做的工作。
    您可以在这里进行真正的验证。
    lodash 提供了许多方便的方法来检查类型

    value: {
      required: true,
      validator: v => true
    },
    

    【讨论】:

    • 现在我想它不应该允许未定义的?‍♂️所以我会做这样的事情......validator: v => !_.isUndefined(v)
    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 2022-08-04
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    相关资源
    最近更新 更多