Subscribe on changes!

Reactive default props

avatar
Aug 16th 2021

What problem does this feature solve?

At this moment this is impossible to set reactive default value of prop depending on other prop.

  props: {
    prop1: {
      type: String,
      required: true
    },
    prop2: {
      type: String,
      default: (props) => props.prop1
    }
  }

prop2 keeping initial value regardless of prop1 changings. Is this expected behavior? I'm using computed to deal with this case, but it will be great to use simple default value instead.

What does the proposed API look like?

May it be reactive?

avatar
Aug 17th 2021

Please be clear about the meaning of the "initial value", there is no reason why it needs to be reactive.

avatar
Aug 17th 2021
// component1.vue
<template>
  <span>Prop1: {{ prop1 }}</span>
  <span>Prop2: {{ prop2 }}</span>
<template>
<script>
export default {
  name: 'Component1',
  props: {
    prop1: {
      type: String,
      required: true
    },
    prop2: {
      type: String,
      default: (props) => props.prop1
    }
  }
}
</script>
// component2.vue
<template>
  <button @click="prop1 = 'bar'">Change prop1 value</button>
  <component1 :prop1="prop1" />
</template>
<script>
import { ref } from 'vue'
import Component1 from './component1.vue'
export default {
  name: 'Component2',
  components: { Component1 },
  setup() {
    const prop1 = ref('foo')
    return { prop1 }
  }
}
</script>

Before the click on 'Change prop1 value' we will see: Prop1: foo Prop2: foo After the click: Prop1: bar Prop2: foo

prop2: { default: (props) => props.prop1 } means value of prop2 depends on value of prop1 if value of prop2 is not set explicitly, doesn't it?

avatar
Aug 17th 2021

In that case you should use a computed, not a default value for the prop.