天天看點

Vue 計算屬性與偵聽器

偵聽器

<div id="app">
    {{msg}}
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            msg: 'hello vue'
        },
        watch: {
            msg: function (newval,oldval){
                console.log('newval is:' + newval)
                console.log('oldval is:' + oldval)
            }
        },
    })
</script>
           

當msg中的值發生變化時,偵聽器就會偵聽到,同時則會執行偵聽器中的事件

watch 隻能監聽目前或這個指定值的變化

computed 隻要是包含在function中變量值任意一個值,對應傳回的值都會發生變化

計算屬性

<div id="app">
    {{msg}}
    <p>
        {{msg1}}
    </p>
</div>
<script>
    var arr = 'new test'
    var app = new Vue({
        el: '#app',
        data: {
            msg: 'hello vue',
            another: 'another hello vue!!'            
        },
        watch: {
            msg: function (newval,oldval){
                console.log('newval is:' + newval)
                console.log('oldval is:' + oldval)
            }
        },
        computed: {
            msg1: function() {
                return 'computed:' + this.msg + ',' + this.another + ',' + arr
            }
        },
    })
</script>
           

watch和computed的差別:

watch:監聽一個變量或一個常量的變化,單一的一個或一個數組

computed:監聽多個變量,前提是在vue的執行個體中

使用場景介紹,watch(異步場景),computed(資料關聯)