In the below html code , I’m simply iterating through 2 variables posts and cp_posts:
HTML CODE
<div v-if="loading">
loading...
</div>
<div v-else>
<p style="background:#ebebeb" v-for="post in posts">
{{post}}
</p>
<p style="background:#ebaaeb" v-for="post in cp_posts">
{{post}}
</p>
</div>
</div>
In the below Vue script, I’m making one axios call to demo URL for fetching some dummy data. Once the request is done I’m storing response data into locally defined variable i.e temp, after that I’m assigning temp to Vue data variables posts and cp_posts.
After assignment I’m changing posts variable, that’s it.
const URL = 'https://reqres.in/api/users';
new Vue({
el: '#app',
data() {
return {
loading: true,
posts: [], // add posts here so reactivity is working, also undefined would be OK
cp_posts: []
}
},
created() {
//this.loading = true --> not needed already set in data
axios.get(URL).then((response) => {
// console.log(response.data, this)
var temp = response.data.data
this.posts = temp
this.cp_posts = temp
this.posts[0].id = 4444 // <== Here I'm changing value from posts variable which will change cp_posts
this.loading = false
})
}
})
OUTPUT
You can see cp_posts variable ==> id: 4444 also get changes, which should be 1, because I haven’t touch cp_posts variable in above code
variable : posts
{ "id": 4444, "first_name": "George", "last_name": "Bluth", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }
{ "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg" }
{ "id": 3, "first_name": "Emma", "last_name": "Wong", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg" }
variable : cp_posts
{ "id": 4444, "first_name": "George", "last_name": "Bluth", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg" }
{ "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg" }
{ "id": 3, "first_name": "Emma", "last_name": "Wong", "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg" }
Why cp_post variable also get changes while changing post variable?
2
Answers
In
posts
andcp_posts
, they have the reference oftemp
that make it mutable.So what you can do is you can change this line
this.cp_posts=temp
to
this.cp_posts=JSON.parse(JSON.stringify(temp))
This will solve your problem. JSFiddle Link
The reason why
cp_posts
is also changed is that in JSarrays
andobjects
are reference type values which means they reference to address of the value in Memory. If you change the value they all changes. One way I found to solve is from this medium post: