1.3计算属性computed

computed必须是纯函数

纯函数:固定的输入得到固定的输出


扩展:
函数柯里化:函数返回函数
1.3计算属性computed
1.3计算属性computed
<div id="box">
    {{ name.substring(0,1).toUpperCase()+name.substring(1)}}
</div> 

<script>
    var vm = new Vue({
        el:"#box",
        data:{
            name:"da"
        }
    })
</script>



计算属性computed:
<div id="box">
    {{ changeword }}
</div> 

<script>
    var vm = new Vue({
        el:"#box",
        data:{
            name:"da"
        },
        computed:{
            changeword:function(){
                return this.name.substring(0,1).toUpperCase() + this.name.substring(1);
            }
        }
    })
</script>


与methods的区别:
在标签里多次调用menthods方法,console.log执行多次;
而在标签里多次调用computed属性,console.log执行一次,调用缓存结果,
所以:
- 计算属性是基于他们的依赖进行缓存的,(存在js对象里)
- 计算属性只有在他的相关依赖发生改变时才会重新求值






v-model: 双向数据绑定  常用于表单元素
watch:监听
<div id="box">
    <p>单价:<input type = "text"  v-model="price"/></p>
    <p>数量:<input type = "text"  v-model="num"/></p>
        <p>总额:<span>{{sum}}</span></p>
</div> 

<script>
    var vm = new Vue({
        el:"#box",
        data:{
            price:100,
            num:1,
            sum:0
        },
        watch:{
            "num":function(){
                var sum = this.price*this.num;
                if(sum>1000){
                    this.sum = sum;
                }else{
                    this.sum = sum +100;
                }
            }
            "price":function(){
                var sum = this.price*this.num;
                if(sum>1000){
                    this.sum = sum;
                }else{
                    this.sum = sum +100;
                }
            }

        },

    })
</script>
          

//计算属性:
<div id="box">
    <p>单价:<input type = "text"  v-model="price"/></p>
    <p>数量:<input type = "text"  v-model="num"/></p>
        <p>总额:<span>{{getsum}}</span></p>
</div> 

<script>
    var vm = new Vue({
        el:"#box",
        data:{
            price:100,
            num:1,
            sum:0
        },

        computed:{
            getsum:function(){
                var sum = this.price*this.num;
                if(sum>1000){
                    this.sum = sum;
                }else{
                    this.sum = sum +100;
                }
            }
        }

    })
</script>

与watch区别:
watch:只能监测data属性中的单个变量的改变,代码冗余
computed:自动检测依赖,代码更精简





计算属性 set

给计算属性赋值 (意义不大)

1.3计算属性computed

1.3计算属性computed
1.3计算属性computed


1.3计算属性computed


不建议这么做,代码难以控制
1.3计算属性computed








相关文章:

  • 2021-08-17
  • 2021-07-28
  • 2021-11-28
  • 2021-05-22
  • 2022-01-26
  • 2022-12-23
猜你喜欢
  • 2021-04-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
  • 2021-11-06
  • 2021-09-13
相关资源
相似解决方案