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'). And when I changed data while the computed function was still not be called and the data (styleObj.width) was still 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
calcWidthfunction never be called? I think it will be called twice, at the beginning and in 2 sec, but it never be called. Why?Why the
styleObj.widthhas always been undefined?