1. 程式人生 > 實用技巧 >分別使用watch,computed屬性計算兩個數之和

分別使用watch,computed屬性計算兩個數之和

現在有個需求,給a一個input,b一個input ,然後用output標籤顯示兩者計算之和

有兩種方法:一是使用監聽屬性,一種是使用computed屬性計算。

同時明白,Vue例項中的資料來源有兩方面,一種是資料模型,一種是computed物件計算後返回的值

法一:

使用監聽屬性 :(資料來源於資料模型)

<div id="app">
{{msg}}
<br>
a :<input type="text" v-model.number="a">
<!-- <br> -->

+b <input type="text" v-model.number
="b"> <!-- <br> --> = <!-- <br> --> <output>{{total}}</output> </div> <script> new Vue({ el:"#app", data:{ msg:"hello", a:0, b:0, total:0 }, methods:{ },
//監聽 偵聽 watch:{ a(newValue,oldValue){ // console.log(newValue,oldValue); this.total=this.a +this.b; }, b(newValue,oldValue){ // console.log(newValue,oldValue); this
.total=this.b+this.a; } } }) </script> </body>

使用監聽屬性有點大材小用,因為監聽屬性大多用來監聽在資料變化時執行非同步或開銷較大的操作,在這裡只能略微瞭解一下它的作用。

法二:

使用computed物件(資料來源於計算屬性)

<body>
<div id="app">
{{msg}}
<br>
a <input type="text" v-model.number="a">
+b <input type="text" v-model.number="b">
=
<output>{{total}}</output>
</div>
    <script>
        new Vue({
            el:"#app",
            data:{
                msg:"hello",
                a:0,
                b:0,
            },
            methods:{
            },
            computed:{
                    total()
                    {
                        return this.a+this.b;
                    }
                }
          
        })
    </script>

注意,當使用computed來進行計算時,資料模型中不需要再寫入total變數名~

計算屬性是基於它們的響應式依賴進行快取的。只在相關響應式依賴發生改變時它們才會重新求值。而每次呼叫函式都會導致函式的重新執行。

以上就是該需求的兩種計算方式。