Search code examples
javascriptvue.jsdefaultvue-props

What is the purpose of the default value in props in vue if vue still throws an error?


I'm trying to understand whether prop validation is for the developer or the user. I intentionally left a component empty

I did not pass a value (by the way, what is this passed value called?): <card />
The correct way: <card :name="name" />

props:{
    name: { default: "John Doe" }

However, when I leave the component empty, without passing a value, Vue uses the default value to populate the value in the template section while leaving an error in the console: Property or method "name" is not defined on the instance but referenced during render.

What if I want to have a default? I will continue to get that error.


Solution

  • Prop validation is useful for both developers and users, but optional.

    I think the issue lies with this line (I refactored the input to 'myName' to explain): <card :name="myName" />

    The error is coming through because myName is not defined properly before it is passed to the component.

    These will work as static examples:

    • <card name="Jesse" /> Because name is not bound with : or v-bind:
    • <card :name="'Jesse'" /> Because name is bound here, but to a literal string 'Jesse'

    <card :name="myName" /> will work, you just need to assert that myName is not undefined.

    myName itself can be a prop in the parent component too if you like, Eg: props: { myName: { default: "Jesse"} }