Vue 计算属性computed

1.什么是计算属性,我们知道在前面学习vue入门程序的时候,一般都是通过mustache语法,从data里拿数据,然后显示,但有时候会出现,一些数据并不可以直接拿来用,而是要经过以一系列的操作后,才能使用,这时候,computed发挥了它的作用,其实method也可以实现,对某些数据进行处理再返回,那为什么要存在computed呢,那是因为computed提供了一个缓存机制,方法每调用一次都会执行一次,而计算属性,在第一次调用时,会执行一次,之后再调用时,不会再执行,数据已经被放到了缓存里面。
2.例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="content">
    <h2>{{getName}}</h2>
    <h2>{{getTotalPrice}}</h2>
</div>
<script src="./vue.js"></script>
<script>
        const content = new Vue({
            el: '#content',
            data: {
                firstName: 'chen',
                lastName: 'shu',
                cartoons: [
                    {id: 1,name: '海贼王',price: 100},
                    {id: 2,name: '火影忍者',price: 300},
                    {id: 3,name: '四驱兄弟',price: 1000},
                    {id: 4,name: '灵异的世界',price: 500},
                    {id: 5,name: '一人之下',price: 10000}
                ]
            },
            computed: {
               getName() {
                   return this.firstName + this.lastName
               },
                getTotalPrice() {
                   //遍历数组的三种方式
                 let total = 0
                    for(let i of this.cartoons) {//拿到的是每一个元素
                        total += i.price
                    }
                 //    let total = 0
                 //       for(let i in this.cartoons) {//拿到的是每一个元素的索引
                 //           total += this.cartoons[i].price
                 //       }
                 //    let total = 0
                 //    for(let i = 0; i < this.cartoons.length; i++) {
                 //        total += this.cartoons[i].price
                 //    }
                return total
                }
            }
        })
</script>
</body>
</html>

3.结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值