当你读取一个变量的时候会触发该变量的getter.
当你修改该变量时候会触发他的setter.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="div">
<input v-model="changeFirstNameFn">
<input v-model="changeSecondNameFn">
<br />
全名:<input id="full" v-model="fullName">
</div>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var a=new Vue({
el:"#div",
data:{
firstName:"",
lastName:"",
fullName:""
},
computed:{
changeFirstNameFn:{
get:function(){ // get 函数,返回绑定的“姓” 的输入框的value 值
return this.firstName
},
set:function(newVal){ //set函数是当数据发生变化时调用.监听到 “姓”的变化,执行set 函数
this.firstName=newVal
this.fullName=newVal+" "+ this.lastName
}
},
changeSecondNameFn:{
get:function(){
return this.lastName},
set:function(newVal){ //set 函数是当数据发生变化时调用
this.lastName=newVal
this.fullName=this.firstName+" "+newVal
}
}
}
})
</script>
</html>
网页效果:(以 “姓” 这个输入框为例)
1. <input > 用 v-model 双向绑定 "changeFirstNameFn" :<input v-model="changeFirstNameFn">
2. get 函数:这里 设置了返回 this.firstName。
1) this.firstName 初始值为 data 设置的默认值;
2) 当 “姓” 这个输入框获取新的值后,由于 set 函数设置了,this.firstName=newVal ,也就是 firstName 会被赋值为输入框的内容(例如:输入“郑”,这个“郑” 就是新输入值 newVal。所以 get函数设置后,return this.firstName 返回 “郑”)
changeFirstNameFn:{
get:function(){ // get 函数,返回绑定的“姓” 的输入框的value 值
return this.firstName
},
3. set 函数 :
1) 当 “姓” 这个输入框获取新的值后,由于 set 函数设置了,this.firstName=newVal ,也就是 firstName 会被赋值为输入框的内容(例如:输入“郑”,这个“郑” 就是新输入值 newVal )
2) “名” 输入框同上。
3) 全名:<input id="full" v-model="fullName"> “全名” 输入框通过 v-model 动态绑定 fullName ,
响应两个 set 函数中 this.fullName=newVal+" "+ this.lastName 和 this.fullName=this.firstName+" "+newVal (通过响应 “姓” 和 “名” 的变化,改变“全名”这个输入框的内容)