首页 > 编程 > JavaScript > 正文

vue中的计算属性实例详解

2019-11-19 12:54:39
字体:
来源:转载
供稿:网友

什么是计算属性

模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。例如:

<div id="example"> {{ message.split('').reverse().join('') }}</div>

这里的表达式包含3个操作,并不是很清晰,所以遇到复杂逻辑时应该使用Vue特带的计算属性computed来进行处理。

计算属性(computed)用于处理复杂逻辑

computed:{}

computed做为vue的选项是固定的

例子:

<div id="itany">  <p>{{mes}}</p>  <p>{{count}}</p></div><script src="../js/vue.js"></script><script>  new Vue({    el:'#itany',    data:{      mes:'hello vue'    },    computed:{      count:function(){                //切割    翻转   拼接        return this.mes.split(' ').reverse().join('---')      }    }  })</script>

输出结果为:

hello vue

vue---hello

练习

要求:点击button按钮使数字以对应的价格改变


Image 2.png

代码如下:

<div id="itany">  <button v-on:click="num">总和</button>  <p>{{arr}}</p></div><script src="../js/vue.js"></script><script>  new Vue({    el:'#itany',    data:{      name:{price:2,count:0},      names:{price:4,count:0},      see:true    },    methods:{      num:function(){        this.name.count++,        this.names.count++      }    },    computed:{      arr:function(){        return this.name.price*this.name.count+this.names.price*this.names.count      }    }  })</script>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表