calbro
calbro

Reputation: 21

Reactive default prop value

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

Upvotes: 2

Views: 561

Answers (2)

DengSihan
DengSihan

Reputation: 3007

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
     }
  }

Upvotes: 1

Tmier
Tmier

Reputation: 1

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

Upvotes: 0

Related Questions