计算属性的 setter 和 getter
方法一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性、方法、侦听器</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
{{fullName}}
{{age}}
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
firstName:"Dell",
lastName:"Lee",
age:28
},
//计算属性
computed:{
fullName:function(){
console.log("计算了一次");
return this.firstName + " " + this.lastName
}
}
})
</script>
</body>
</html>
方法二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的 setter 和 getter</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
firstName:"Dell",
lastName:"Lee",
},
//计算属性
computed:{
fullName:{
get:function(){
return this.firstName + " " + this.lastName
},
set:function(value){
console.log(value);
}
}
}
})
</script>
</body>
</html>
输出:
改变fullName的值,第一个是输出的,第二个是返回的
做出下列改动:var arr = value.split(""); this.firstName = arr[0]; this.lastName = arr[1];
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的 setter 和 getter</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
firstName:"Dell",
lastName:"Lee",
},
//计算属性
computed:{
fullName:{
get:function(){
return this.firstName + " " + this.lastName
},
set:function(value){
var arr = value.split("");
this.firstName = arr[0];
this.lastName = arr[1];
console.log(value);
}
}
}
})
</script>
</body>
</html>
这时的值随输入的也发生变化,compute 的特点:当依赖的值发生变化则会重新计算,当重新输入值时导致
firstName 的值发生变化,进而导致 compute 重新计算 fullName 的值发生变化