vue中的计算属性实例详解

2019-11-14,,,

什么是计算属性

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

<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>

您可能感兴趣的文章:

  • 详解Vue的computed(计算属性)使用实例之TodoList
  • Vue计算属性的使用
  • Vue中计算属性computed的示例解读
  • Vue computed计算属性的使用方法
  • Vue.js第三天学习笔记(计算属性computed)
  • Vue.js每天必学之计算属性computed与$watch

《vue中的计算属性实例详解.doc》

下载本文的Word格式文档,以方便收藏与打印。