The right way for VueJS to edit scroll without changing parent data

There is an object in my vue parent component user.

If I pass this custom object to the child component as a prop:

<child :user="user"></child>

and in my child component I am updating user.name, it will also be updated in the parent.

I want to edit the user object in the child component without changing, which is reflected in the user object that is in the parent component.

Is there a better way to do this than the cloning of an object using: JSON.parse(JSON.stringify(obj))?

+8
source share
4 answers

JSON.

const child = {
  props:["user"],
  data(){
    return {
      localUser: Object.assign({}, this.user)
    }
  }
}

localUser ( , ) .

Edit

, , , @user3743266

, . . , , . , ... , - . , v-ifs, . , - ?

:

Vue.component('edit-user', {
  template: `
  <div>
    <input type="text" v-model="localUser.name">
    <button @click="$emit('save', localUser)">Save</button>
    <button @click="$emit('cancel')">Cancel</button>
  </div>
  `,
  props: ['user'],
  data() {
    return {
      localUser: Object.assign({}, this.user)
    }
  }
})

, @user3743266 , . user , localUser - . , , , .

Vue.component('edit-user', {
  template: `
  <div>
    <input type="text" v-model="localUser.name">
    <button @click="$emit('save', localUser)">Save</button>
    <button @click="$emit('cancel')">Cancel</button>
  </div>
  `,
  props: ['user'],
  data() {
    return {
      localUser: Object.assign({}, this.user)
    }
  },
  watch:{
    user(newUser){
        this.localUser = Object.assign({}, newUser)
    }
  }
})

fiddle.

, / . , .

  watch:{
    user(newUser){
      if (condition)
        this.localUser = Object.assign({}, newUser)
    }
  }

, , , , , , , .

+16

" " " " . , , , . , , , , ? , . , user, JSON.parse(JSON.stringify()), , Vue. ? , , , ?

, , , ? ? - ( - ), .

0

,

data() {
return { localUserData: {name: '', (...)}
}
(...)
created() {
    this.localUserData.name = this.user.name;
}

, . , localData .

0

in the above solutions, the observer will not start the first linking, only when changing the details. To solve this problem, use immediate = true

watch: {
  test: {
    immediate: true,
    handler(newVal, oldVal) {
      console.log(newVal, oldVal)
    },
  },
}
0
source

All Articles