[英]why vue.js computed get undefined
I just wanna use Vue computed, but I get undefined(styleObj.width)
, and it seems that the computed function was not called (didn't log 'computed').我只想使用 Vue 计算,但我得到
undefined(styleObj.width)
,并且似乎没有调用计算函数(没有记录“计算”)。 And when I changed data while the computed function was still not be called and the data (styleObj.width)
was still undefined
.当我在计算函数仍未被调用且数据
(styleObj.width)
仍为undefined
时更改数据。
The code is simple and I hope you know what I'm talking about.代码很简单,我希望你知道我在说什么。
<!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
<meta charset="utf-8" />
<title>JS Bin</title>
<style>
#app {
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="app" :style="styleObj"></div>
<script>
var vm = new Vue({
el: '#app',
data: {
num: 100,
styleObj: {
width: this.calcWidth, // always be undefined even num has changed
},
},
computed: {
calcWidth() {
console.log('computed') // never log 'computed' which means the
// calcWidth not be called
return this.num + 'px'
},
},
})
setTimeout(() => {
vm.num = 200
}, 2000)
</script>
</body>
</html>
I have 2 questions:我有两个问题:
Why the calcWidth
function never be called?为什么永远不会调用
calcWidth
函数? I think it will be called twice, at the beginning and in 2 sec, but it never be called.我认为它会在开始和 2 秒内被调用两次,但它永远不会被调用。 Why?
为什么?
Why the styleObj.width
has always been undefined?为什么
styleObj.width
总是未定义?
There are several problems.有几个问题。
The way it's written currently, the this
in width:this.calcWidth
will not be referring to the correct object.它当前的编写方式,宽度中的
this
width:this.calcWidth
不会引用正确的对象。 It needs to be within a function to get the scoping correct.它需要在一个函数中才能获得正确的范围。 That is easily fixed by changing
data
to a function.这很容易通过将
data
更改为函数来解决。
The next problem is that computed properties are not available within the data
function.下一个问题是计算属性在
data
函数中不可用。 The order is roughly:顺序大致是:
Things lower down that list can use things higher up the list, not the other way around.该列表下方的内容可以使用列表上方的内容,而不是相反。
Instead you can make the whole style object a computed property:相反,您可以使整个样式对象成为计算属性:
computed: {
styleObj () {
return {
width: this.num + 'px'
}
}
}
or if you prefer to retain calcWidth
:或者如果您更喜欢保留
calcWidth
:
computed: {
styleObj () {
return {
width: this.calcWidth
}
}
}
You can't use computed property
in data
, because data
evaluates before the computed properties
did.您不能在
data
中使用computed property
,因为data
在computed properties
之前计算。
You can use a watcher
to achieve the intended result:您可以使用
watcher
来达到预期的结果:
watch: {
num(val) {
this.styleObj.width = val + 'px'
}
}
If num
changes the watcher
get triggered.如果
num
更改,则触发watcher
。 See the documentation on that.请参阅相关文档。
Edit: You can use the argument immediate
to trigger directly:编辑:您可以使用参数
immediate
直接触发:
watch: {
num: {
immediate: true,
handler(val) {
this.styleObj.width = val + 'px'
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.