【问题标题】:Vue.js Weird thing happens when you store a getter in a variableVue.js 将 getter 存储在变量中时会发生奇怪的事情
【发布时间】:2020-02-20 08:31:21
【问题描述】:

我是日本人,英语不好,对不起。

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

但我不知道原因。

为什么会这样?

【问题讨论】:

    标签: javascript node.js typescript vue.js getter


    【解决方案1】:

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

    让我们来看看发生的各个阶段:

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

    【讨论】:

    • 我预计 console.log(temp) 的结果会是 { someStrItem: 'str' }。所以,和你说的一样。
    • 但它是 { someStrItem: 'newStr' } 。我想知道为什么会这样。
    • 啊,我明白你的意思了。这里的问题实际上是微不足道的——您的代码实际上按预期工作。当您console.log(temp) 时,它确实 输出{ someStrItem: 'str' }但是 因为this.getObj.someStrItem懒惰地 评估,当您登录temp 时,它只是输出this.getObj 而不评估其中的任何内容。它只是输出位于this.getObj 引用的值。您可以通过在console.log(temp) 之后放置debugger 语句来尝试此操作。这将暂停你的代码执行,它会让你看到它正在工作!
    • changeObj () { const temp = this.getObj; console.log(temp); debugger; this.someObj.someStrItem = 'newStr'; }
    • 非常感谢。使用调试器的结果是 { someStrItem: "str" }。所以你在写。但是,“懒惰评估”对我来说有点难以理解......(T_T)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多