Vue学习笔记_计算属性VS侦听器VS方法

官网中说,对于任何复杂逻辑,你都应当使用计算属性。

  • computed
    直接用计算属性的名字作为变量名。
    计算属性是基于它们的依赖进行缓存的。计算属性只有在它的相关依赖发生改变时才会重新求值。
    即:computed中的待计算的值所依赖的值,有改变时,才会触发计算属性重新计算,这样可以提高性能。

  • methods:

与computed的区别在于,在页面上有其他非计算属性内依赖的元素需要重新渲染时,计算属性会先看所依赖的值是否改变,若未改变,则不重新计算,而写在methods中的方法,在有需要渲染时,会将methods中的方法全部都执行一次。相较效率会低一些。

在demo中表现为:在other输入框中输入值,只有methods会被打印出来,说明又多执行了一次。

  • watch:

监听两个变量的值地改变,在任意一个改变后,就进行计算,和computed属性效果一样,但是代码麻烦了些。

** 计算属性的set方法
计算属性默认的是get方法,若要写set方法,则如例子中的total0。
测试方法如下,给total0赋值:
vm.total0='2'
之后,就会触发total0的set方法;
而如果给total赋值,则会报错:
[Vue warn]: Computed property “total” was assigned to but it has no setter.

Demo:

    <div id="app">
        <input v-model="one" /> + 
        <input v-model="two" /> 
        <div>computed reslut = {{total}}</div>
        <div>computed set reslut = {{total0}}</div>
        <div>methods reslut = {{total2()}}</div>
        <div>watch reslut = {{total3}}</div>
        <div>other:<input v-model="other"/></div>
    </div>

    <script>
        var vm = new Vue({
            el:'#app',
            data:{
                one:'',
                two:'',
                other:'',
                total3:''
            },
            computed:{
                //默认get方法
                total:function(){
                    console.log('computed');
                    return this.one+this.two;
                },
                //set,get方法
                total0:{
                    get:function(){
                        console.log('computed get');
                        return this.one+this.two;
                    },
                    set : function (v){
                        console.log('computed set');
                        this.one = 'abc';
                    }
                }
            },
            methods:{
                total2:function(){
                    console.log('methods');
                    return this.one+this.two;
                }
            },
            watch:{
                one:function(v){
                    this.total3 = v + this.two;
                    console.log('watch one');
                },
                two:function(v){
                    this.total3 = this.one + v;
                    console.log('watch two');
                }
            }
        });
    </script>

按照1,2,3的顺序输入,执行结果如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Dorothy1224/article/details/81270756
今日推荐