1

I saw an weird behavior in v-model but i don't know what should i call it. is it normal or weird.

HTML Markup:

<div id="app">
 <div>EditItem: {{ editItem }}</div>
 <div>FormData: {{ formData }}</div>
 <input type="text" v-model="formData.name" label="name" />
</div>

Script:

new Vue({
 el: '#app',
 data: {
   editItem: { name: 'Mr. Coder' },
   formData: null,
 },
 created() {
   this.formData = this.editItem
 },

So my question is when I change the input value of formData using v-model it is also change the editItem value. but why? I have already attached the value of formData using created method. So it should change the formData only. Can anyone explain me about this behavior in detail or is there any way that it doesn't change the editItem value but can change only formData using v-model? Thanks.

For your reference see the JSFiddle URL: https://jsfiddle.net/nhxjp8m1/

2 Answers2

2

This is not a Vue specific behaviour but rather a JavaScript one. When you wrote

this.formData = this.editItem

It did not create a copy of editItem but rather formData now REFERS to editItem. Therefore changing formData directly changes editItem and vice-versa.

I believe the behaviour you seeks requires copying editItem into formData using Object.assign().

For more information about JavaScript, I suggest going through this website.

CRUD DS
  • 456
  • 2
  • 5
0

Well editItem is a non-primitive type. If you assign some other variable with your non primitive type you copy the reference to it rather then the value itself.

You did a pass by reference

You could use the spread operator to make a copy of it without an reference:

 created() {
   this.formData = { ...this.editItem }
 },
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Yeah, I have learned it now. This article helps me a lot. Here is the article -https://javascript.info/object-copy – CoderByte71 Oct 19 '20 at 07:38