1.代码复用
computed: {
position() {
return ((!this.right || this.right < 0)
? 0
: (this.right > 75)
? 80
: this.right)
}
},
用计算属性,可多个地方同时应用 position 这个属性,
反之,直接写在 template 里面相应复用只能 ctrl/c ctrl/v
2.可读性
不用计算属性, template 里是这样的
:style="
{ right:(!this.right || this.right < 0)
? 0
: (this.right > 75)
? 80
: this.right
+'vw',}">
代码逻辑混杂在 template 里
用了计算属性, template 里是这样的
template 内部是声明式的,可读性更好
3 代替监听器,监听多个属性变化执行相关操作
computed: {
transition() {
if (this.open) setTimeout(() => {
this.right = 80
}, 0);
if (this.close) setTimeout(() => {
this.right = 0
}, 0);
return (this.open || this.close
? 'all 0.2s ease-out'
: '')
}
},
在这个 transition 函数里不仅返回了一个值,同时监听了 open,close 的改变对 right 属性进行更新。
如果觉得《vue 计算属性和data_Vue 计算属性问题?》对你有帮助,请点赞、收藏,并留下你的观点哦!