Vue.js 将 getter 存储在变量中时会发生奇怪的事情

Vue.js Weird thing happens when you store a getter in a variable

我是日本人,英语不好,抱歉。

这是一个非常简单的vue代码。

<template>
  <div id="app">
    <button @click.once="changeObj">
      Click
    </button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      someObj: {
        someStrItem: 'str'
      }
    }
  },
  computed: {
    getObj () {
      return this.someObj
    }
  },
  methods: {
    changeObj () {
      const temp = this.getObj
      console.log(temp) // → { someStrItem: 'newStr' }
      this.someObj.someStrItem = 'newStr'
    }
  }
}
</script>

奇怪的是在 changeObj 函数内部。

我预计 console.log(temp) 的结果会是

{ someStrItem: 'str' }

因为

this.someObj.someStrItem = 'newStr'

我在

之后这样做
  const temp = this.getObj
  console.log(temp)

但结果是

{ someStrItem: 'newStr' }

我不知道为什么会这样。

嗯,其实我平时不做这种事。

而且,我可以预料到会发生这种情况,因为我将 getter returns 对象存储在变量中。

但是不知道是什么原因

为什么会这样?

为什么 temp 应该是 { someStrItem: '' }

让我们来看看事件的各个阶段:

  1. 您的组件被实例化为 data:
{
  someObj: {
    someStrItem: 'str'
  }
}
  1. getObj 自动 computed
{
  someStrItem: 'str'
}
  1. 当您在 changeObj 中调用 console.log(temp) 时,this.getObj 仍然具有
  2. 的值
{
  someStrItem: 'str'
}