我将axios响应存储到两个不同的“数据”变量中,如果更改一个变量,它将自动更改另一个变量

时间:2019-04-04 11:18:29

标签: vue.js vuejs2

在下面的html代码中,我只是简单地遍历2个变量posts和cp_posts:

HTML代码

  <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>

在下面的Vue脚本中,我正在对演示URL进行一次axios调用,以获取一些虚拟数据。请求完成后,我将响应数据存储到本地定义的变量中,即 temp ,然后将 temp 分配给Vue数据变量 posts cp_posts

分配后,我要更改 posts 变量,就是这样。

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
    })
  }
})

输出

您会看到 cp_posts 变量==> id:4444也得到了更改,应该为1,因为我没有触摸上面代码中的 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" }

变量: 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" }

为什么 cp_post 变量在更改 post 变量时也会获得更改?

参考链接: https://jsfiddle.net/LokeshKhandare/31zvmcwp/2/

2 个答案:

答案 0 :(得分:0)

postscp_posts中,他们引用了temp使其可变。 因此,您可以做的就是更改此行

this.cp_posts=temp

this.cp_posts=JSON.parse(JSON.stringify(temp))

这将解决您的问题。 JSFiddle Link

答案 1 :(得分:0)

cp_posts也被更改的原因是,在JS中,arraysobjects 引用类型 的值,这意味着它们引用内存中值的地址。如果更改值,它们都会全部更改。我发现要解决的一种方法是从此medium post

    //Deep Clone
    let a = [{ x:{z:1} , y: 2}];
    let b = JSON.parse(JSON.stringify(a));
    b[0].x.z=0
    console.log(JSON.stringify(a)); //[{"x":{"z":1},"y":2}]
    console.log(JSON.stringify(b)); // [{"x":{"z":0},"y":2}]