One can avoid using the JSON
object.
const child = {
props:["user"],
data(){
return {
localUser: Object.assign({}, this.user)
}
}
}
Utilize localUser
(or choose any other name) within your child component.
Edit
I customized a fiddle from another answer to illustrate the aforementioned concept, prompting @user3743266's inquiry:
Understanding this myself, I have found it incredibly helpful. Your sample functions effectively. In the child component, you have created an element in data that duplicates the prop, and the child operates with that copy. Intriguing and practical, but... it is uncertain to me
when the local copy gets updated if something alters the parent. I made adjustments to your fiddle by eliminating the v-ifs so everything is visible and replicating the edit component. If you modify the name in one component, the other does not receive any updates?
The current component appears as follows:
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)
}
}
})
Due to my decision to use a locally duplicated user, @user3743266 rightly notes that the component does not update automatically. The property "user" is updated but "localUser" is not. In such a case, if automatic updating of local data upon property changes is desired, implementing a watcher would be necessary.
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)
}
}
})
An updated version of the fiddle is provided.
This approach grants complete control over when or if local data should be updated or emitted. For instance, a condition check might be warranted before altering the local state.
watch:{
user(newUser){
if (condition){
this.localUser = Object.assign({}, newUser)
}
}
}
As mentioned previously, there are scenarios where leveraging mutable object properties proves beneficial, while instances like this may require stricter control.