我是日语,我的英语不好,对不起。

这是一个非常简单的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存储在变量中。

但是我不知道原因。

为什么会这样?

最佳答案

为什么temp永远是{ someStrItem: '' }

让我们看一下发生的阶段:


您的组件使用data实例化:


{
  someObj: {
    someStrItem: 'str'
  }
}



getObj自动作为computed


{
  someStrItem: 'str'
}



当您在console.log(temp)中调用changeObj时,this.getObj的值仍为


{
  someStrItem: 'str'
}

09-11 18:25
查看更多