计算属性的getter和setter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>setter和getter</title>
</head>
<body>
<div id="app">
<h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'kobe',
lastName: 'Bryant',
},
computed: {
fullName: {
//计算属性一般只设置get方法,只读的,我们不希望可以随意修改计算属性,故删除set方法
set: function (newValue) {
//根据空格对name进行截取,分别存入lastName和firstName
const names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[1];
},
get:function () {
return this.firstName+' '+this.lastName;
}
},
//由于是只读属性,可以简写成下面方法
/* fullName:function () {
return this.firstName+' '+this.lastName;
}*/
}
});
</script>
</body>
</html>
注意点:
1.计算属性有get和set方法,注意名字不要自己取,就是固定的
2.百分九十的情况下都会省略set方法,为只读属性,就可以进行简写。
fullName:function () { return this.firstName+' '+this.lastName;}
3.当然可以设置set方法,只要有就会执行这个方法。上边例子中采用split方法以空格为标志,分割名字,然后分别存入firstName和lastName.
4.如果不是简写模式,属性名后不要加function,因为这是一个属性,内部有get和set方法。加上会报错。
fullName: {
//计算属性一般只设置get方法,只读的,我们不希望可以随意修改计算属性,故删除set方法
set: function (newValue) {
//根据空格对name进行截取,分别存入lastName和firstName
const names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[1];
},
get:function () {
return this.firstName+' '+this.lastName;
}
},