[Vuejs]-V-model nested value from schema is always undefined

1👍

prop1: { type: Object as PropType<Prop1 | null>, default:()=> ({}) },

Here you’re setting the default value of prop1 as an empty object. It makes sense then that prop1.prop2 is undefined, because by default prop2 doesn’t exist on prop1. Even if some very short time after component creation do you pass down an actual value to prop1 from a parent component, you still need to make sure that your template code can handle prop1 as it is before it has any value. I have two possible suggestions:

  1. Provide default properties when defining prop1, something similar to:
prop1: { type: Object as PropType<Prop1 | null>, 
default:()=> ({
  prop2: {
    hourly: {
      click: {
        value: null
      }
    }
  }}) 
},
  1. Use v-if to not render the text field until the prop has a value.:
<v-text-field v-if="validProp" type="text" label="Click" outlined dense v-model="prop1.prop2.hourly.click.value"/>
computed: {
  validProp() {
    return this.prop1?.prop2?.hourly?.click?.value !== undefined;
  },
},

You could optionally abstract this into a generic isLoading boolean prop set by the parent based on the current fetch/loading status of prop1

👤yoduh

Leave a comment