Vue中computed与method的区别

computed和method都可以当做方法使用

computed和method的区别

区别一:

computed调用是属性调用,不需要加括号,

methods是函数调用,需要加括号

html代码:

<div id="app">
        <input type="text"v-model.number="a">
        <input type="text"v-model.number="b">
        <p v-cloak>结果:{{handle()}}</p>
        <p v-cloak>结果:{{handleCom}}</p>
</div>

js代码:

<script src="vue.js"></script>
<script>
    var vm = new Vue({
        el:"#app",
        data:{
            a:"",
            b:"",
            sum:"",
        },
        methods:{
            handle(){
                return this.a+this.b;
            }
        },
        computed:{
            handleCom(){
                return this.a+this.b;
            }
        }
    })


</script>
如果handle()不加括号,
<p v-cloak>结果:{{handle()}}</p>

会在浏览器中打印  

function () { [native code] }

如果handleCom加括号,则会报错

TypeError: handleCom is not a function"

区别二:

 

computed是 当下次所依赖的函数没有发生改变时,再次调用时,会从缓存中读取数据

 

methods是 没有缓存存数据,每次调用每次执行,无论值有没有改变

<script>
    var vm = new Vue({
        el:"#app",
        data:{
            a:"",
            b:"",
            sum:"",
        },
        methods:{
            handle(){
                console.log("handle()被调用了")
                return this.a+this.b;
            }
        },
        computed:{
            handleCom(){
                console.log("handleCom被调用了")
                return this.a+this.b;
            }
        }
    })


</script>

handle()只要光标移入console.log()就会被执行

handleCom()输入框中值发生改变,才会执行

 

posted @ 2019-05-21 13:34  一点元气  阅读(2480)  评论(0)    收藏  举报