我是日语,我的英语不好,对不起。
这是一个非常简单的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'
}