vue:vue的计算属性操作和缓存

什么是计算属性
在这里插入图片描述
计算属性的基本操作

    <div id="app">
        <h2>{{first+' '+last}}</h2>
        <h2>{{first}} {{last}}</h2>
        <h2>{{getTwo()}}</h2>

<!-- 计算属性 -->
        <h2>{{mergeTwo}}</h2>

    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                first:'one',
                last:'two'
            },
            // 计算属性
            computed:{
                // mergeTwo本质是一个属性
                mergeTwo:function(){
                    return this.first+' '+this.last
                }
            },
            methods: {
                getTwo(){
                    return this.first+' '+this.last
                }
            }
        });
    </script>

计算属性的get和set

<body>
    <div id="app">
        <h2>{{fullName}}</h2>
    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                firstName:'zhangsan',
                lastName:'lisi'
            },
            computed: {
                // 属性对象 一般情况下只需要实现的是get方法,下面有更简洁的写法
                fullName: {
                    // set一般需要传参
                    set:function(newValue){
                        // console.fullName(newValue)

                        const name = newValue.split(' ')
                        this.firstName = name[0]
                        this.lastName = name[1]
                    },
                    get:function(){
                        return this.firstName + ' ' + this.lastName
                    }
                
                }

                // 所以可以简写成
                // fullName:function(){
                //     return this.firstName + ' ' + this.lastName
                // }

            },
            methods: {}
        });
    </script>

计算属性的缓存,和methods的区别

计算属性相对于methods方法不仅简化了编码,而且也具有更高的性能,用method方法如果需要多次使用的话它就会被多次调用,但是计算属性会被缓存,只会调用一次。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值