Vue学习06_计算属性

计算属性

当我们有时候需要对要展示的数据进行处理时,比如输入姓氏与名称,例如:张三丰,接收到的数据有两个,姓氏:张,以及名:三丰,按照之前的mustache语法写也是可以写,但是比较复杂,也可以写一个函数来获取两个数据的组合,但是这里都显得很复杂,因此,Vue引入计算属性这一东西:

  1. 计算属性的基础用法
    示例代码:
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue练习-计算属性的基本使用</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <p>{{getFullName()}}</p>
        <p>{{fullName}}</p>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                surname: '张',
                name: '三丰'
            },
            // 计算属性
            computed: {
                // 语法与函数差不多,但是他是一个属性,因此取名按照属性取名为fullName
                fullName: function () {
                    return this.surname + ' ' + this.name;
                }
            },
            methods: {
                getFullName: function () {
                    return this.surname + ' ' + this.name;
                }
            }
        });
    </script>
</body>

</html>

运行结果:
在这里插入图片描述
在这里可以看到,函数的写法比计算属性的写法复杂,计算属性的写法更加简洁,也更加容易理解:
2.计算属性的复杂用法:
上面的例子可能觉得计算属性的用法并不是很大,但是当涉及到的数据量比较多时,假如不使用计算属性,那么写起来将十分的复杂,例如计算数组books的总价格时:
示例代码:

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue练习</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <p>{{totalPrice1}}</p>
        <p>{{totalPrice2}}</p>
        <p>{{totalPrice3}}</p>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                books: [
                    { id: 01, bookname: '三国演义', price: 98 },
                    { id: 02, bookname: '水浒传', price: 88 },
                    { id: 03, bookname: '西游记', price: 68 },
                    { id: 04, bookname: '红楼梦', price: 78 },
                ]
            },
            computed: {
                // 方法1:for循环遍历
                totalPrice1: function () {
                    let totalPrice = 0;
                    for (let i = 0; i < this.books.length; i++) {
                        totalPrice += this.books[i].price;
                    }
                    return totalPrice;
                },
                // 方法2:for in 遍历
                totalPrice2: function () {
                    let totalPrice = 0;
                    for (let i in this.books) {
                        totalPrice += this.books[i].price;
                    }
                    return totalPrice;
                },
                // 方法3:for of 遍历
                totalPrice3: function () {
                    let totalPrice = 0;
                    for (let book of this.books) {
                        totalPrice += book.price;
                    }
                    return totalPrice;
                }
            },
            methods: {

            }
        });
    </script>
</body>

</html>

运行结果:
在这里插入图片描述
在这里时,利用到了三种遍历方式对数组的价格进行了遍历,代码量更加小。

  1. 计算属性的setter和getter方法:
    一般来说,一个方法调用时必须要方法名加括号,如fullName(),但是计算属性写的格式与函数方法差不多,调用时却不需要加括号,这是因为使用计算属性时,调用了计算属性的get方法,因此不需要加括号:
    示例代码:
    <div id="app">
        <P>{{fullName}}</P>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                surname: '张',
                name: '三丰'
            },
            computed: {
                // 计算属性一般只有get方法,所以计算属性一般为只读属性
                fullName: {
                    set: function () {

                    },
                    get: function () {
                        return this.surname + this.name;
                    }
                }
            },
            methods: {}
        });
    </script>

运行结果:
在这里插入图片描述
一般的计算属性并没有set方法,因为我们不希望别人对我们的属性进行操作,所以计算属性一般为只读属性,又因为计算属性只有get方法,所以可以简写成函数的形式,如fullName : function(){ …}
计算属性一般没有set方法,不代表计算属性不能设置set方法!
示例代码:

            computed: {
                // 计算属性一般只有get方法,所以计算属性一般为只读属性
                fullName: {
                    // 一般没有不代表一定没有,也可以为计算属性设置set方法,当值发生改变时,调用set方法
                    set: function () {
                        console.log("调用了计算属性的set方法!")
                    },
                    get: function () {
                        return this.surname + this.name;
                    }
                }
            },

运行结果:当计算属性的值发生改变时,调用计算属性的set方法
在这里插入图片描述
计算属性的set方法当计算属性的值发生改变时调用,因此计算属性需要有一个参数,该参数为新的计算属性的值:
示例代码:

set: function (newValue) {
                        console.log("调用了计算属性的set方法!");
                        console.log("新的计算属性的值为:" + newValue)
                    },

运行结果:
在这里插入图片描述
计算属性的set方法在计算属性改变时调用,一般来说得到新的计算属性,需要对他进行保存,例如上面例子的姓氏和名称,就要将他分别拆开保存:
示例代码:

                    // 一般没有不代表一定没有,也可以为计算属性设置set方法,当值发生改变时,调用set方法
                    set: function (newValue) {
                        console.log("调用了计算属性的set方法!");
                        console.log("新的计算属性的值为:" + newValue);
                        const names = newValue.split(' ');
                        this.surname = names[0];
                        this.name = names[1];
                        console.log("surname的值为:" + this.surname);
                        console.log("name的值为:" + this.name);
                    },

运行结果:计算属性的值还未发生改变时:
在这里插入图片描述
改变计算属性的值:
在这里插入图片描述
4. 计算属性computed与方法methods的对比:

示例代码:computed与method同时使用4次,但是computed只调用一次,而methods却要调用四次

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue练习</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- 通过methods方法调用 -->
        <p>{{getFullName()}}</p>
        <p>{{getFullName()}}</p>
        <p>{{getFullName()}}</p>
        <p>{{getFullName()}}</p>
        <!-- 通过计算属性computed调用 -->
        <p>{{fullName}}</p>
        <p>{{fullName}}</p>
        <p>{{fullName}}</p>
        <p>{{fullName}}</p>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                surname: '张',
                name: '大宝'
            },
            computed: {
                fullName: function () {
                    console.log("调用了计算属性computed");
                    return this.surname + ' ' + this.name;
                }
            },
            methods: {
                getFullName: function () {
                    console.log("调用了方法methods");
                    return this.surname + ' ' + this.name;
                }
            }
        });
    </script>
</body>

</html>

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值