模板中的表达式虽然方便,但也只能用来做简单的操作。如果在模板中写太多逻辑,会让模板变得臃肿,难以维护。因此我们推荐使用计算属性来描述依赖响应式状态的复杂逻辑。
<template>
<div>
<p>{{ msg }}</p>
<p>{{ msg.length>0 ? "yes" : "no" }}</p>
</div>
</template>
<script>
export default{
data(){
return{
msg:"你好世界"
}
},
}
</script>
我们可以利用计算属性computed 函数来优化上述代码
<template>
<div>
<p>{{ msg }}</p>
<p>{{choseMsg}}</p>
</div>
</template>
<script>
export default{
data(){
return{
msg:"你好世界"
}
},
//computed可以承载计算方法
computed:{
choseMsg(){
this.msg.length>0 ? "yes" : "no";
}
}
}
</script>