rpf3
rpf3

Reputation: 691

VueJS Props as Initial Value to Data

I have the following VueJS component and am trying to set an initial value to a local data variable as described here. The component code is as follows:

<template>
  <p>
    name: {{ name }} <br/>
    model: {{ model }}
  </p>
</template>

<script>

export default {
  props: {
    name: {
      type: String
    }
  },

  data: function () {
    return {
      model: this.name
    }
  }
}
</script>

The issue I'm facing is that when the component renders only the "name" is rendered while the "model" is empty. I've been banging my head against this for a while now and feel like I'm missing something glaringly obvious.

Upvotes: 1

Views: 1862

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14043

You don't show the parent's use of this component, but based on the commentary, the most likely problem is that the parent is rendering the child with an initial null value for the name prop. That gets rendered in the child. The parent then updates its name prop which is reflected in the child. But because the child has already been created, its model data is already set (to null). You can fix this with a watcher.

watch: {
    name() {
        this.model = this.name;
    }
}

Upvotes: 1

Related Questions