想象一下你在餐厅当服务员,有两种工作方式,你会选哪种?
// 需要手动更新每个元素
function updateCounter(change) {
var count = parseInt($('#counter').text());
var newCount = count + change;
// 更新计数显示
$('#counter').text(newCount);
// 更新进度条
var progress = (newCount / 10) * 100;
$('#progress').css('width', progress + '%');
// 更新状态文字
if (newCount > 5) {
$('#status').text('高!').addClass('warning');
} else {
$('#status').text('正常').removeClass('warning');
}
// 如果忘了更新某个地方...
// 界面就会不一致!😱
}
// 只需要定义数据和规则
data() {
return {
count: 0
}
},
computed: {
// 进度自动计算
progress() {
return (this.count / 10) * 100;
},
// 状态自动判断
status() {
return this.count > 5 ? '高!' : '正常';
},
isWarning() {
return this.count > 5;
}
}
// 模板里只需要声明关系
<template>
<div class="status" :class="{ warning: isWarning }">
{{ status }}
</div>
</template>