当你读取一个变量的时候会触发该变量的getter.
当你修改该变量时候会触发他的setter.
<div id="div">
<input v-model="firstName" >
<input v-model="lastName">
<br />
全名:<input v-model="fullNameFn">
</div>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!--引入vue js 外部文件-->
<script> //vue js 代码写在这里
var a=new Vue({
el:"#div",
data:{
firstName:"zz",
lastName:"ling",
fullName:"zz ling"
},
computed:{
fullNameFn:{ //get 函数是读取数据发生时调用
get:function(){
return this.fullName
},
set:function(newVal) //set 函数是当数据发生变化时调用
{this.fullName=newVal,
newVal=newVal.split(" "),
this.firstName=newVal[0],
this.lastName=newVal[1]
}
}
}
})
网页效果:
set 函数:
这里全名 zz ling 是触发了 fullNameFn: 这个函数的 get 函数,获取数据
get:function(){
return this.fullName // this.fullName 是数据属性里面原来有的数据
},
set 函数:
修改全名 fullNameFn 对应的元素数据时,触发了 set 函数
set:function(newVal) //set 函数是当数据发生变化时调用. newVal 就是新参数
{ this.fullName=newVal,
newVal=newVal.split(" "),
this.firstName=newVal[0],
this.lastName=newVal[1]
}