使用vue开发一个小项目的时候,由于模板内的style需要使用计算属性,
在computed内部计算出的值却无法使用;
在data内部进行了检测,发现this是可以检测到的,但是this下的多个属性均为undefined
贴上代码
computed:{
offsetTop:function(){
return (this.$el.offsetWidth-this.$el.offsetHeight)/2+'px';
}
},
data:function(){
console.log(this);
console.log(this.offsetTop);
return{
styleObject: {
top: this.offsetTop+'px'
}
}
},

求路过的大神帮看看是怎么回事。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
computed是在data后面初始化的,data执行的时候,在computed定义的属性还不存在呢。
受楼上高人的启发,找到问题的所在
最后的解决方案可能不是很优雅,但是好赖是解决了。
解决思路是这样的,既然是由于data属性在computed前面先初始化的
那就先设置data内的w ,h属性,然后在computed内部对w ,h进行计算。
关键一步,是在mounted钩子函数内部对w ,h重新复制(这时候$el已经挂载上了)
之后就触发了computed的重新计算,完成页面的重新渲染,问题解决。
最后再次致谢 @lxyqy