0
votes

I have a Vue child component which receives data from parent through props. What I want it to set the value of "name" property like below:

<template>
    <input v-model="name" type="text" placeholder="Name" id="name">   <!-- this does not work -->

    {{ this.productdata.name }} <!-- this works -->
    {{ name }} <!-- this DOES NOT work -->
</template>

export default {
        data() {
            return {
                name: this.productdata.name
            }
        },
        props: ['productdata'],
        methods: {
            setProductData()
            {
                this.name = this.productdata.name;
            }
        },
        mounted() {
                // because "name: this.productdata.name" doesn't work I tried to make it like below... No success.
                this.setProductData();
        },
}

I guess this have something to do with when Vue child component props becoming reactive. I have fount working solution but it's not elegant at all:

mounted() {
            setTimeout(() => {
                this.setProductData();
            }, 2000);
        },

Any suggestions how to do it better?

2

2 Answers

2
votes

You could try using a watcher for your productData which sets your name the moment productData changes. This worked for me when I had a similar problem.
Therefore add in your export defaults

export defaults {
...
  watch: {  
    productdata: function () {
      this.setProductData()
    }  
  },
...
}  
1
votes

You can change hook mounted to created

created() {
            this.setProductData();
        }

Also you can use Computed Properties and Watchers

computed: {
    name: function () {
      return this.productdata ? this.productdata.name : '';
    }
  }