Vue——computed与methods的区别

<div id="app">
    <p>{{getFullName()}}</p>
    <p>{{fullName}}</p>
</div>

<script src="js/vue.js"></script>
<script>
    let vue = new Vue({
        el: '#app',
        data: {
            firstName: '张',
            lastName: '三'
        },
        methods: {
            getFullName(){
                return this.firstName+" "+this.lastName
            }
        },
        computed: {
            fullName(){
                return this.firstName+" "+this.lastName
            }
        }
    })
  1. 从上面例子中很容易看出,虽然两者都能通过 {{}} 引用,但 methods 需要加括号。
<div id="app">
    <p>{{getFullName()}}</p>
    <p>{{fullName}}</p>
    <p>{{getFullName()}}</p>
    <p>{{fullName}}</p>
    <p>{{getFullName()}}</p>
    <p>{{fullName}}</p>
    <p>{{getFullName()}}</p>
    <p>{{fullName}}</p>
</div>

<script src="js/vue.js"></script>
<script>
    let vue = new Vue({
        el: '#app',
        data: {
            firstName: '张',
            lastName: '三'
        },
        methods: {
            getFullName(){
                console.log('methods')
                return this.firstName+" "+this.lastName
            }
        },
        computed: {
            fullName(){
                console.log('computed')
                return this.firstName+" "+this.lastName
            }
        }
    })
</script>

  1. 当多次调用时,computed 有缓存,如果没有改变,多次引用只会调用一次

    而 methods 没有缓存,每次引用都会调用一次

    所有就对属性计算方面来看, computed 优于 methods

posted @ 2020-08-09 17:46  布小星  阅读(369)  评论(0编辑  收藏  举报