iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

網頁前端框架 Vue 3 從頭開始系列 第 10

vue.js 3.x 學習手冊 (10) 計算屬性的setter

如前一篇所提Computed能夠自動監看指定的數據,當數據發生變化後自動重新計算結果,但如果我們想直接修改Computed的結果,在沒有使用Setter的狀態下程式是會發生錯誤的,下面範例同樣是BMI的計算,但我們期望使用者可以自行改變BMI的數據,藉以觀察體重上的變化:

HTML
<div id="app">
    <p>Height:<input type="number" v-model="height">CM</p>
    <p>Weight:<input type="number" v-model="weight">KG</p>
    <p>BMI:<input type="number" v-model="bmi"></p>
    <p>Suggestion:{{ bmiMessage }}</p>
</div>
Javascript
const app = Vue.createApp({
    data() {
        return {
            height: 180,
            weight: 80,
        }
    },
    computed: {
        bmi: function(){
            return (this.weight / (Math.pow((this.height/100), 2))).toFixed(2);
        },
        bmiMessage: function () {
            if (this.bmi > 35) {
                return "重度肥胖";
            } else if (this.bmi >= 30 && this.bmi < 35) {
                return "中度肥胖";
            } else if (this.bmi >= 27 && this.bmi < 30) {
                return "輕度肥胖";
            } else if (this.bmi >= 24 && this.bmi < 27) {
                return "過重";
            } else if (this.bmi >= 18.5 && this.bmi < 24) {
                return "正常範圍";
            } else {
                return "體重過輕";
            }
        },
    },
}).mount('#app');

使用上結果如下:
Yes

如果要讓頁面能夠正常使用,就會用到我們標題中提到的Setter,程式可以改為:

Javascript
const app = Vue.createApp({
    data() {
        return {
            height: 180,
            weight: 80,
        }
    },
    computed: {
        bmi: {
            get: function () {
                return (this.weight / (Math.pow((this.height / 100), 2))).toFixed(2);
            },
            set: function (val) {
                console.log("Run Setter");
                this.weight = ((Math.pow((this.height / 100), 2)) * val).toFixed(2)
            }
        },
        bmiMessage: function () {
            if (this.bmi > 35) {
                return "重度肥胖";
            } else if (this.bmi >= 30 && this.bmi < 35) {
                return "中度肥胖";
            } else if (this.bmi >= 27 && this.bmi < 30) {
                return "輕度肥胖";
            } else if (this.bmi >= 24 && this.bmi < 27) {
                return "過重";
            } else if (this.bmi >= 18.5 && this.bmi < 24) {
                return "正常範圍";
            } else {
                return "體重過輕";
            }
        },
    },
}).mount('#app');

使用上的結果如下:
Yes

以上就是針對Vue的計算屬性Computed中Setter的案例說明,期望能對大家產生幫助,也可以動手玩看看範例檔


上一篇
vue.js 3.x 學習手冊 (9) 計算屬性
系列文
網頁前端框架 Vue 3 從頭開始10
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言