Home > Software engineering >  Reactive default prop value
Reactive default prop value

Time:12-09

In the below:

  props: {
    id: {
      type: String,
      default() {
        return this.$route.params.id;
      },
    },
  },

then, supposing the parent component does not provide a value, I would expect the value of the id prop to change whenever the route changes to a new id. However this does not seem to be the case. Is my understanding correct? And is there a way to achieve reactivity here? Otherwise I'm thinking of setting required: false on it and then I'll have to have some computedId computed field, but I'd rather do it straight in the props section

CodePudding user response:

Wouldn't it be better to just use computed? Or use watch to listen to the id and perform the force refresh function, but I don't really know how to set the action directly in the props

CodePudding user response:

It's not a good idea to provide a default value base on a variable directly in props, the default in props is considered to provide a static value instead of a reactive value


use a computed value instead of props in your template may be a better practice

<div>{{ computedId }}</div>


  props: {
    id: {
      type: String,
    },
  },
  computed: {
     computedId() {
        return this.value || this.$route.params.id
     }
  }
  • Related