Vue 2 - How to set default type of array in props

偶尔善良 提交于 2021-02-04 12:55:48

问题


I have my Vue component, which is taking an array of objects as a prop. I often use prop validation, especially for 'default' value feature.

in this case I have:

props: {
    items: Array
}

but I'd like it to have like in Typescript or React:

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

etc.

Is it possible to achieve? Otherwise I need to use computed data as map just to set the defaults


回答1:


I created example: jsFiddle, that might can help you, and yes... you can return the default value as a array:

ES6

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



回答2:


ES6 variety For an Array

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

...And for an Object

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

A couple related resources:

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


来源:https://stackoverflow.com/questions/41553596/vue-2-how-to-set-default-type-of-array-in-props

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!