1. 程式人生 > >vue中計算屬性,方法,偵聽器的一個比較

vue中計算屬性,方法,偵聽器的一個比較

通過以下例子我們來做一個比較,請看程式碼:

<div id="app">
    {{fullName}}<br>
    {{fullName2()}}<br>
    {{fullName3}}<br>
    age:{{age}}
</div>

<script>
    var vm = new Vue({
        el: "#app",
        data: {
            firstName: "cai",
            lastName: "quan",
            fullName3: "cai quan",
            age: 21
        },
        //計算屬性(擁有快取機制,只要對應的值沒改變則不會執行,比methods方法實現更好,和watch監聽器實現效能相近,但程式碼更少)
        computed: {
            fullName: function () {
                console.log('計算屬性:' + '計算了一次');
                return this.firstName + " " + this.lastName
            }
        },
        //方法
        methods: {
            fullName2: function () {
                console.log('方法:' + '計算了一次');
                return this.firstName + " " + this.lastName
            }
        },
        //監聽器 監聽firstName,lastName的變化 控制檯輸入:vm.firstName = 'wang'
        watch: {
            firstName: function () {
                console.log('監聽器:' + '計算了一次');
                this.fullName3 = this.firstName + " " + this.lastName
            },
            lastName: function () {
                console.log('監聽器:' + '計算了一次');
                this.fullName3 = this.firstName + " " + this.lastName
            }
        }
    })
</script>

我們再看在控制檯中執行的效果:

當我們修改與fullName無關的屬性age時,只有方法重新執行了一次,由此可見methods方法不如watch監聽器和computed計算屬性好,再看程式碼量,computed更少。所以計算屬性更優一些。