Home > other >  Vue3 updating data value is updating prop too
Vue3 updating data value is updating prop too

Time:12-19

Don't know if this is the normal behaviour, I'm kind of new to Vue, but it's driving me nuts. Hope someone here have any clue about what's happpening...

This is my export:

props: [
    'asset', //--- asset.price = 50
],
data() {
    return {
        local_asset: this.asset
    }
}

Then, I update the value of a local_asset value with v-model:

<input type="number" v-model="local_asset.price" @change="test" />

And on filling the input with i.e. 100, it results in prop asset being changed too:

methods: {
    test() {
        console.log(this.local_asset.price)  //--- console >> 100
        console.log(this.asset.price)        //--- console >> 100
    }
}

Am I doing it wrong? Sorry if my code is a nonsense. Please help...

CodePudding user response:

You need to copy value , not reference:

Vue.component('Child', {
  template: `
    <div >
      <input type="number" v-model="local_asset.price" />
      <div>data: {{ local_asset }}</div>
    </div>
  `,
  props: [
    'asset',
  ],
  data() {
    return {
      local_asset: {...this.asset}
    }
  },
})

new Vue({
  el: '#demo',
  data() {
    return {
      asset: {price: 50}
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div>prop: {{ asset }}</div>
  <Child :asset="asset" />
</div>

CodePudding user response:

If your data in primitive (String, Number, BigInt, Boolean, undefined, and null) you can use

 data() {
       return {
       local_asset: JSON.parse(JSON.stringify(this.asset))
       }
    }
  • Related