如前一篇所提Computed能夠自動監看指定的數據,當數據發生變化後自動重新計算結果,但如果我們想直接修改Computed的結果,在沒有使用Setter的狀態下程式是會發生錯誤的,下面範例同樣是BMI的計算,但我們期望使用者可以自行改變BMI的數據,藉以觀察體重上的變化:
<div id="app">
<p>Height:<input type="number" v-model="state.height">CM</p>
<p>Weight:<input type="number" v-model="state.weight">KG</p>
<p>BMI:<input type="number" v-model="bmi"></p>
<p>Suggestion:{{ bmiMessage }}</p>
</div>
<script>
const { reactive, computed } = Vue;
const app = {
setup(){
const state = reactive({
height: 180,
weight: 80,
})
const bmi = computed(() => {
console.log("Run BMI Computed");
return state.weight / (Math.pow((state.height / 100), 2));
})
const bmiMessage = computed(() => {
console.log("Run BMI Message Computed");
if (bmi.value > 35) {
return "重度肥胖";
} else if (bmi.value >= 30 && bmi.value < 35) {
return "中度肥胖";
} else if (bmi.value >= 27 && bmi.value < 30) {
return "輕度肥胖";
} else if (bmi.value >= 24 && bmi.value < 27) {
return "過重";
} else if (bmi.value >= 18.5 && bmi.value < 24) {
return "正常範圍";
} else {
return "體重過輕";
}
})
return { state, bmi, bmiMessage };
}
}
const myVue = Vue.createApp(app).mount("#app");
</script>
如果要讓頁面能夠正常使用,就會用到我們標題中提到的Setter,程式可以改為:
<script>
const { reactive, computed } = Vue;
const app = {
setup(){
const state = reactive({
height: 180,
weight: 80,
})
const bmi = computed({
get:() => {
return (state.weight / (Math.pow((state.height / 100), 2))).toFixed(2);
},
set:(val) => {
console.log("Run Setter");
state.weight = ((Math.pow((state.height / 100), 2)) * val).toFixed(2);
}
})
const bmiMessage = computed(() => {
console.log("Run BMI Message Computed");
if (bmi.value > 35) {
return "重度肥胖";
} else if (bmi.value >= 30 && bmi.value < 35) {
return "中度肥胖";
} else if (bmi.value >= 27 && bmi.value < 30) {
return "輕度肥胖";
} else if (bmi.value >= 24 && bmi.value < 27) {
return "過重";
} else if (bmi.value >= 18.5 && bmi.value < 24) {
return "正常範圍";
} else {
return "體重過輕";
}
})
return { state, bmi, bmiMessage };
}
}
const myVue = Vue.createApp(app).mount("#app");
</script>
使用上的結果如下:
以上就是針對Vue的計算屬性Computed中Setter的案例說明,期望能對大家產生幫助,也可以動手玩看看範例檔。