computed深入

计算属性set/get

  • 计算属性 (单向)

    在computed属性对象中定义计算属性的方法,在页面使用{{方法名}}来显示计算的结果

  • 监听属性 (单向)

    通过vm对象的$watch()或watch配置来监听指定的属性,当属性变化时,回调函数自动调用,在函数内部进行计算。

  • 计算属性高级 (双向)

    通过geter/setter实现对属性数据的显示和监视,计算属性存在缓存,多次读取只执行一次getter计算。

const vm = new Vue({
        el: "#demo",
        data: {
            firstName: "A",
            lastName: "B",
            fullName2: "A-B"
        },
        computed: {
            fullName1() {
                return this.firstName + "-" + this.lastName;
            },
            fullName3: {
                // 回调函数:当读取当前属性值,根据相关数据变化 计算并返回当前属性值
                get() {
                    return this.firstName + "-" + this.lastName;
                },
                // 回调函数: 监听属性值发生改变时回调,更新相关的属性数据
                set(value) { //value 就是fullName3最新值
                    let name = value.split("-");
                    this.firstName = name[0];
                    this.lastName = name[1];
                }
            }
        },
        watch: {
            firstName(newValue, oldValue) {
                this.fullName2 = newValue + "-" + this.lastName;
            },
            lastName(newValue, oldValue) {
                this.fullName2 = this.firstName + "-" + newValue;
            }
        }
    })

你可能感兴趣的:(computed深入)