test004.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>计算属性和监视</title></head><body><!--1.计算属性 在在computed属性对象中定义计算属性的方法 在页面中使用{{方法名}}来显示计算的结果2.监视属性: 通过vm对象的$watch()或watch配置来监视指定的属性 当属性变化时,回调函数自动调用,在函数内部进行计算3.计算属性高级 通过getter/setter实现对数据的显示和监视 计算属性存在缓存,多次读取只执行一次getter计算 getter:属性的get方法 setter:属性的set方法--><div id="demo"> 姓: <input type="text" placeholder="First Name" v-model="firstname"><br> 名: <input type="text" placeholder="Last Name" v-model="lastname"><br> 姓名1(单向):<input type="text" placeholder="Full Name1" v-model="fullname1"><br> 姓名2(单向):<input type="text" placeholder="Full Name2" v-model="fullname2"><br> 姓名3(双向):<input type="text" placeholder="Full Name3" v-model="fullname3"><br> <!--按理说应该执行fullname1()4遍,但观察console执行了一遍,第一遍肯定执行,缓存到了容器中了--> <!--fullname1作为k,值作为value,用的时候先从缓存中取,取不到再去调函数--> <p>{{fullname1}}</p> <p>{{fullname1}}</p> <p>{{fullname1}}</p></div><script type="text/javascript" src="../js/vue.js"></script><script type="text/javascript"> const vm= new Vue({ el:'#demo', data:{ firstname:'赵', lastname:'云', fullname2:'赵 云' }, computed:{ //1.什么时候执行:初始化显示执行/相关的data的属性数据发生变化 //2.用来做什么?计算并返回当前属性的值 fullname1(){//计算属性的一个方法,方法的返回值作为属性值 console.log('fullname1') //this就是vm对象 return this.firstname+''+this.lastname }, fullname3:{ //回调函数 计算并返回当前属性的值 //回调函数满足三个条件:1.你定义的,2.你没有调用,3.但最终他执行了 //关于回调函数:1.什么时候调用?2.用来做什么? //1.当需要读取当前属性值时回调2.根据相关的数据计算并返回当前属性的值 get(){ return this.firstname+''+this.lastname }, //回调函数,监视当前属性值的变化,当属性值发生改变时调用,更新相关的属性数据 set(value){//value就是fullname3的最新属性值 const names=value.split(' ') this.firstname=names[0] this.lastname=names[1] } } }, watch:{//配置监视属性 //里面是个回调函数function //如果不需要以前的值了,可以这样写function(newVal) firstname: function(value){//firstname发生了 变化,我们需要去修改fullname1 console.log(this) //this就是vm对象 this.fullname2=value+' '+this.lastname } } }) //所有vm的方法都以$开头 vm.$watch('lastname',function(value){ //更新fullname2 this.fullname2=this.firstname+' '+value })</script></body></html>2.页面截图
来源:https://www.cnblogs.com/curedfisher/p/12014495.html