vue(5) - 计算属性的使用-computed

 首先,computed的使用方法:

computed:{
  b:function(){ //默认调用get
    return 值
  }
}

 

 完整用法:

computed:{
  b:{
         get:  //默认的写法
         set:  //设置值的
      }
}    

 

具体实例: 

      <script>
             window.onload=function(){
                var vm= new Vue({
                    el:'#box',
                    data:{
                        a:1,                       
                    },
                    computed:{
                        b:function(){//b在这里不是一个函数,只是一个属性
                            //写业务逻辑代码
                            //return 1 //返回多少b的值就是多少,不return,没有值
                            return this.a+1
                        }
                    }
                });    
                document.onclick=function(){
                    vm.a=101;
                }
           };           
     </script>
    //html
    <div id="box">    a=> {{a}}   <br/>    b=> {{b}}    </div>

 结果:点击页面时,

a=>101

b=>102 

 

    <script>
             window.onload=function(){
                var vm= new Vue({
                    el:'#box',
                    data:{
                        a:1,                       
                    },
                    computed:{
                        b:{
                            get:function(){   //默认是第一种那样的写法
                                return this.a+2;
                            },
                            set:function(val){
                                this.a=val
                            }
                        }
                    }
                });    
                document.onclick=function(){
                    vm.b=10;
                }
           };           
        </script>

    //html
       <div id="box">
          a=>    {{a}}
          <br/>
          b=>    {{b}}
      </div>

结果:点击页面时,

a=>10

b=>12 

        

 *和data的区别是 computed 放一些业务逻辑的代码,切记放return

posted @ 2017-07-12 20:41  sunwy927  阅读(187)  评论(0编辑  收藏  举报