• 计算属性中包含getset方法
  • 当计算属性中所依赖的属性的值发生变化时,计算属性更新(调用get方法)
  • 使用set方法为计算属性设置值后会自动调用get方法

2.1 完整写法

//完整写法
fullName: {
    //getter
    get: function () {
        //此时的this是vm对象
        console.log(this);
        console.log("get被调用了");
        return this.firstName + " - " + this.lastName;
    },
    //setter
    set: function (newValue) {
        console.log("set被调用了");
        var names = newValue.split("-");
        this.firstName = names[0];
        this.lastName = names[1];
    }
}

2.2 简写

fullName(){
    return this.firstName+'-'+this.lastName;
}

注意点:

  • 简写的写法不能包含set方法
  • 返回值为get方法

调用: {{计算属性名称}}

<div id="root">
    姓: <input type="text" v-model="firstName"><br/><br/>
    名: <input type="text" v-model="lastName"><br/><br/>
    全名: <span>{{fullName}}</span>
</div>
最后修改:2023 年 01 月 31 日
如果觉得我的文章对你有用,请随意赞赏