【vue】computed 和 watch

計算屬性:computed  監聽多個變量且變量是在vue實例中(依賴某個變量,變量發生改變就會觸發)css

偵聽器:   watch        監聽一個變量的變化html

使用場景:watch(異步場景)   computed(數據聯動)vue

 demo:app

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>computed 和 watch</title>
    <script src="https://cdn.bootcss.com/vue/2.6.10/vue.common.dev.js"></script>
</head>
<body>
    <div id="app">
        watch:{{msg}}
        <div>computed:{{msg1}}</div>
    </div>
    <script>
        var app = new Vue({
            el:'#app',
            data:{
                msg:'message',
                other:'word'
            },
            watch:{
                msg(newVal,oldVal){
                    console.log('msg:' + newVal);
                    console.log('msg:' + oldVal);
                }
            },
            computed:{
                msg1(){
                    return this.msg  +'   ' + this.other
                }
            }
        });
        app.msg = 'Hello';
        app.other = '小紅'
    </script>
</body>
</html>
相關文章
相關標籤/搜索