利用computed
实现属性计算,代码案例如下:
<div id="app"> 姓:<input type="text" v-model="firstName" /> 名:<input type="text" v-model="secondName" /> 全名:{{fullName}} </div> <script> var app = new Vue({ el:"#app", data:{ firstName:"", secondName:"" }, //属性计算:只有在依赖的数据发生改变是才会重新计算,未改变则使用之前计算的缓存结果 computed:{ fullName:function(){ return this.firstName+this.secondName; } /* 或这样写也可 fullName(){ return this.firstName+this.secondName; } */ } }); </script>
侦听器指的是监听某个数据或计算属性发生变化,可以触发相关的操作,这里使用watch
去侦听
需求:在上面案例的基础上,我们需要统计姓名被修改的总次数
<div id="app"> 姓:<input type="text" v-model="firstName" /> 名:<input type="text" v-model="secondName" /> 全名:{{fullName}} 总次数:{{count}} </div> <script> var app = new Vue({ el:"#app", data:{ firstName:"", secondName:"", count:0 }, computed:{ fullName:function(){ return this.firstName+this.secondName; } }, //侦听器 watch:{ //侦听firstName变化 /* firstName:function(){ this.count++; }, //侦听secondName变化 secondName:function(){ this.count++; } */ //也可简化为直接对fullName侦听 fullName:function(){ this.count++; } } }); </script>