【Vue】计算属性computed:

本文探讨了Vue.js中计算属性与方法的区别,强调计算属性在多次计算时的性能优势,因为它会缓存结果。示例代码展示了如何在模板中使用`price`和`num`数据来计算总价,通过`getTotalPrice()`方法和`totalPrice`计算属性的多次调用进行比较。计算属性`totalPrice2`进一步展示了如何在计算属性内部复用其他计算属性或方法。
摘要由CSDN通过智能技术生成

当页面中需要多次计算,可以使用计算属性,计算属性只会计算一次,并将计算结果缓存

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <p>单价:{{price}}</p>
    <p>数量:{{num}}</p>
    <p>总价:{{price * num}}</p>
    <hr>
    <p>总价:{{getTotalPrice()}}</p>
    <p>总价:{{getTotalPrice()}}</p>
    <p>总价:{{getTotalPrice()}}</p>
    <hr>
    <p>总价:{{totalPrice}}</p>
    <p>总价:{{totalPrice}}</p>
    <p>总价:{{totalPrice}}</p>
    <hr>
    <p>总价:{{totalPrice2}}</p>
    <p>总价:{{totalPrice2}}</p>
    <p>总价:{{totalPrice2}}</p>
</div>
</body>
</html>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            price: 10,
            num: 8
        },
        methods: {
            getTotalPrice() {
                console.log("getTotalPrice");
                var total = this.price * this.num;
                return total;
            }
        },
        computed: {
            totalPrice() {
                console.log("totalPrice");
                var total = this.price * this.num;
                return total;
            },
            totalPrice2() {
                console.log("totalPrice2");
                return this.getTotalPrice();
            }
        }
    });
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值