Vue-3 計算屬性與偵聽器

根據慕課網的課程做的筆記

計算屬性與偵聽器

  • 偵聽器:watch
  • 計算屬性:computed
  • 使用場景

偵聽器:watch

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="../scripts/vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}
</div>
<script>
  var app=  new Vue({
        el: "#app",
        data: {
            msg: "hello Vue!"
        },
        watch: {
            msg: function (newVal,oldVal) {
                console.log("最新的值爲:" + newVal);
                console.log("以前的值爲:"+oldVal);
            }
        },
        computed: {}
    });
</script>
</body>
</html>

在這裏插入圖片描述
在這裏插入圖片描述

計算屬性:computed

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="../scripts/vue.js"></script>
</head>
<body>
<div id="app">
{{msg}}
<p>{{msg1}}</p>
</div>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            msg: "hello Vue!"
        },
        watch: {
            msg: function (newVal, oldVal) {
                console.log("最新的值爲:" + newVal);
                console.log("以前的值爲:" + oldVal);
            }
        },
        computed: {
            msg1: function () { 
            return 'computed:'+this.msg
            }
        }
    });
</script>
</body>
</html>

在這裏插入圖片描述
在這裏插入圖片描述

watch與computed區別

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="../scripts/vue.js"></script>
</head>
<body>
    <div id="app">
        {{msg}}<br />
        count= {{count}}<br />
        (count+1)*2={{(count+1)*2}}<br />
        計算屬性computed:{{this.msg1}}<br />
        <button type="button" v-on:click="submit">點擊一次,count+1</button>
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                msg: "Hello Vue!!",
                count: 0
            },
            methods: {
                submit: function () {
                    this.count++;
                }
            },
            watch: {
                msg: function (newVal, oldVal) {
                    console.log("最新的值爲:" + newVal);
                    console.log("以前的值爲:" + oldVal);
                }
            },
            computed: {
                msg1: function () {
                    return "computed:" + this.msg + "--" + this.count;
                }
            }
        });
    </script>
</body>
</html>

計算屬性computed:msg和count是msg1的組成部分,當msg或者count值變化時,都會觸發computed中定義的函數,會使msg1改變,而偵聽器只是偵聽了msg的值的變化,只有msg值變化時,纔會觸發watch中定義的函數
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章