我是日本人,英语不好,抱歉。
这是一个非常简单的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: '' }
?
让我们回顾一下事件发生的各个阶段:
- 您的组件将使用
数据
实例化:
{
someObj: {
someStrItem: 'str'
}
}
getObj
自动计算
为
{
someStrItem: 'str'
}
- 当您在
changeObj
中调用console.log(temp)
时,this.getObj
的值仍为
{
someStrItem: 'str'
}
关于javascript - Vue.js 当你将 getter 存储在变量中时会发生奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533936/