0

I've got basic vue props and data:

props: ['person', 'type']
data() {
  return {
    offer: {
      type: 'basic',
      person: 'nurse',
      ...

How can I make my data react to props change? For example if prop person will be 'physican' I want my data offer.person = 'physician'. Oherwise if props value will be empty, I want to have default value of offer.person.

How is the easiest way to achieve this? I tried watchers, computed, but none of them seems to work.

edit: I wrote something like this:

  basicComputed(){
    this.offer.person = this.person
    this.offer.type = this.type      
  },

and then in template:

<template>
  <div>
     {{basicComputed}}
  </div>
</template>

It works, but it seems that it is not a perfect solution. Is there a better way to do it?

gileneusz
  • 1,435
  • 8
  • 30
  • 51
  • You can use `props` directly in your templates if that's what you are looking for. If you do want to use this in the `offer` variable you might have to look into watch/computed properties (see https://stackoverflow.com/questions/45022705/vue-js-passing-props-to-data) – Teun May 04 '18 at 08:37
  • @Teun this is a good idea to use watchers, but what will happen if parent component rerender. This is something like "crate new" component - take a value at start and don't change it – gileneusz May 04 '18 at 08:42

1 Answers1

1

Just change your props to an object and you can use defaults

props: {
  person: {
    default: "some role"
  },
  type: {
    default: "basic"
  }
}

https://v2.vuejs.org/v2/guide/components-props.html#Prop-Validation

tony19
  • 125,647
  • 18
  • 229
  • 307
A. L
  • 11,695
  • 23
  • 85
  • 163
  • thanks for this tip! can I modify this to be an element of offers object? just like: `props: { offer.person: { default: "some role" },` – gileneusz May 04 '18 at 09:53
  • then why not just have `offer` as the prop? so `props: { offer: { default: {person: "some role", type: "basic" } } }` – A. L May 04 '18 at 11:47
  • that's because I use offer array as a placement for my api requests – gileneusz May 04 '18 at 15:07