Blog of CodeJELLOW’S ENGINEERING NOTES
← 返回文章

VUE3(六)计算属性

计算属性computed

本文目录 ⌄

    计算属性是模板对象中的computed,computed是一个对象,里面定义了各种计算属性的方法(getter和setter),可以直接如同变量一般使用。好处是代码简洁且有缓存。

    TEXT
        <template id="my-app">
            <h2>{{fullName}}</h2>
            <h2>{{result}}</h2>
            <h2>{{reverseMessage}}</h2>
        </template>
        <script src="../js/vue.js"></script>
        <script>
            const app={
                template:"#my-app",
                data(){
                    return{
                        firstName: "kobe",
                        lastName: "bryant",
                        score: 80,
                        message: "hello world"
                    }
                },
                computed: {
                    // 定义了一个计算属性叫fullname
                    fullName(){
                        return this.firstName + ' ' + this.lastName;
                    },
                    result(){
                        return this.score >= 60 ? "及格" : "不及格";
                    },
                    reverseMessage(){
                        return this.message.split(' ').reverse().join(' ');
                    }
                }
            };
            Vue.createApp(app).mount("#app");
        </script>

    setter和getter

    computed的完整写法是定义一个对象,并在里面定义get和set方法

    TEXT
                computed: {
                    // fullName的getter和setter方法
                    fullName:{
                        get: function(){
                            return this.firstName + ' ' + this.lastName;
                        },
                        set: function (newValue) {
                            console.log(newValue);
                            const names = newValue.split(" ");
                            this.firstName = names[0];
                            this.lastName = names[1];
                        }
                    }
                }

    如果computed中直接定义一个函数,这是一个语法糖,相当于是定义了getter方法

    TEXT
                    // fullName 的 getter方法
                    fullName: function(){
                        return this.firstName + ' ' + this.lastName;
                    }

    对computed属性赋值时会自动调用set方法。

    通过 RSS 订阅更新 →