Vue中计算属性的 setter 和 getter 以及 简便书写方式的由来

<body>
    <div id="app">
        <h2>{
    
    {
    
    fullSentence}}</h2>
    </div>
    <script src="../JS/vue.js"></script>
    <script>
        const app = new Vue({
    
    
            el:'#app',
            data:{
    
    
                firstName:'Kobe',
                lastName:'Beyant'
            },
            computed:{
    
    
                // fullSentence:function(){
    
    
                //     return this.message + ' ' + this.lastName;
                // }
                
                // 以上写法实质上是如下书写的简写形式

                // 一般只需要实现get方法
                // 而没有set方法,是一个 只读属性
                fullSentence:{
    
    
                    set:function(newValue){
    
    
                        // console.log('------',newValue);
                        const names = newValue.split(' ');
                        this.firstName = names[0];
                        this.lastName = names[1];
                    },
                    get:function(){
    
    
                        return this.firstName + ' ' + this.lastName;
                    }
                }

                
            }
        
        })
    </script>
</body>

简写方式由来:
即将标准写法的setget都取消, fullSentence方法名用来代替get函数名字,即可更加简略,但是其实质还是一个属性,而不是函数。

猜你喜欢

转载自blog.csdn.net/weixin_45664402/article/details/114462512
今日推荐