<template>
    <div >
        <div>{{reverseTitle}}</div>
        <div>{{reverseTitle2()}}</div>
        <button @click="add()">补充货物1</button>
        <div>总价为:{{price}}</div>
    </div>
</template>
<script>
export default {
    data(){
        return {
            package1: {
                count: 5,
                price: 5
            },
            package2: {
                count: 10,
                price: 10
            },
            title: 'Hello Vue!!!'
        }
    },
    computed: {
        price(){
            return this.package1.count*this.package1.price+this.package2.count*this.package2.price  //总价随着货物或价格的改变会重新计算
        },
        reverseTitle(){//计算属性里面的方法,只要引用值没发生变化,那么就不会执行该方法
            console.log('我执行了reverseTitle方法')
            return this.title.split('').reverse().join('')
        }
    },
    methods: {   //对象的方法
        add(){
            this.package1.count++
            this.package2.count++
        },
        reverseTitle2(){//每次页面渲染时就会执行该方法
            console.log('我执行了reverseTitle2方法:', this.title)
            return this.title.split('').reverse().join('')
        }
    }
}
</script>

Vue computed  计算属性

总结:
1.computed 在第一次引用,或引用值改变时才会触发里面的方法(缓存,减少不必要的反复计算)
2.在methods 里面的方法会在页面渲染更新时反复调用(耗费大量性能)
3.使用computed 定义方法后 可以在模板中直接用方法名得到结果 而不需要像methods 这样()使用(方便调用)

相关文章:

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