【问题标题】:Vue 2 - How to set default type of array in propsVue 2 - 如何在道具中设置默认数组类型
【发布时间】:2017-05-24 01:02:27
【问题描述】:

我有我的 Vue 组件,它以对象数组作为道具。 我经常使用道具验证,特别是对于“默认”值功能。

在这种情况下,我有:

props: {
    items: Array
}

但我希望它在 Typescript 或 React 中具有类似的效果:

props: {
    items: Array.of(
        {key: {type: String, default: 'myText'}}
        )
}

等等

有可能实现吗?否则我需要使用计算数据作为地图来设置默认值

【问题讨论】:

    标签: javascript types vuejs2 vue.js


    【解决方案1】:

    我创建了示例:jsFiddle,这可能会对您有所帮助,是的...您可以将默认值作为数组返回:

    ES6

    props: {
        items: {
            type: Array,
            default: () => []
        }
    }
    

    【讨论】:

    • 谢谢,不是我想的那么优雅,但似乎在工作;)
    • Vue 属性默认值不适用于 null,仅适用于 undefined,因此不等同于 if (!items)...。试试小提琴<animals :animal="null"></animals>
    【解决方案2】:

    ES6 变体对于一个数组

    props: {
      arr: {
        type: Array,
        default: () => []
      }
    }
    

    ...对于一个对象

    props: {
      obj: {
        type: Object,
        default: () => ({
          param: value,
          param2: value,
        })
      }
    }
    

    一些相关资源:

    1. https://github.com/vue-styleguidist/vue-styleguidist
    2. https://github.com/vuejs/vue/issues/1032

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-08
      • 2020-08-01
      • 2019-07-14
      • 1970-01-01
      • 2016-12-11
      • 2019-05-08
      • 1970-01-01
      • 2023-02-03
      相关资源
      最近更新 更多