Alber Z
Alber Z

Reputation: 27

Mechanism of updating data in VueJS?

<script>
export default {
  data() {
    return {
      data: {},
      dataTemp: {}
    }
  },
  methods: {
    updateData() {
      let queries = { ...this.$route.query }
      this.data = {
        ...this.data,
        pID: queries.pid,
        sID: queries.sid
      }
      this.dataTemp = {
        ...this.dataTemp,
        pID: queries.pid,
        sID: queries.sid
      }
    }
  }
}
</script>

In the example above, when I update this.data, this.dataTemp will also be changed.

But I think it is not related to each other.

Please explain to me this problem. Thanks!

Upvotes: 0

Views: 39

Answers (1)

Daniel Elkington
Daniel Elkington

Reputation: 3647

This sets the initial values of data and dataTemp to empty objects. Note that they are both different objects though - data !== dataTemp.

data() {
  return {
    data: {},
    dataTemp: {}
  }
}

If someone calls this.updateData(), both are changed because we assign to both data and dataTemp. If you only want to update data, you could change the method to

updateData() {
  let queries = { ...this.$route.query }
  this.data = {
    ...this.data,
    pID: queries.pid,
    sID: queries.sid
  }
}

Upvotes: 1

Related Questions