Default values for Vue component props & how to check if a user did not set the prop?

后端 未结 3 910
星月不相逢
星月不相逢 2021-01-30 12:26

1. How can I set the default value for a component prop in Vue 2? For example, there is a simple movies component that can be used in this way:

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 12:45

    Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

    props: {
      year: {
        default: 2016,
        type: Number
      }
    }
    

    If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

    https://jsfiddle.net/cexbqe2q/

提交回复
热议问题