一、 计算属性(computed)
1、计算属性的定义和原理
1、定义:要用的属性不存在,要通过已有属性计算得来。
2、原理:底层借助了Objcet.defineproperty方法提供的getter和setter。
3、get函数什么时候执行?
(1) 初次读取时会执行一次。
(2)当依赖的数据发生改变时会被再次调用。
4、优势:与methods实现相比,内部有缓存机制(复用),效率更高,调试方便。
5、备注:
(1)计算属性最终会出现在vm上,直接读取使用即可。
(2)如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。
2、基础例子
计算属性有两种写法,当需要修改计算属性的值时用完整写法(即需要set方法),否则用简写形式。
(1)完整写法
<body> <div id="app"> <input type="text" v-model="a"><br> <input type="text" v-model="b"><br> <h1 v-text="full"></h1><br> </div> <!-- 开发环境版本,包含了有帮助的命令行警告 --> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> var vm=new Vue({ el:"#app", data(){ return{ msg:"Hello World!", a:"李", b:"明" } }, computed:{ /*get有什么作用?当有人读取full时,get就会被调用,且返回值就作为full的值 get什么时候调用? 1.初次读取full时。 2.所依赖的数据发生变化时。 */ full:{ get(){ console.log("full get被调用了") return this.a+"-"+this.b }, set(value){ console.log("full set被调用了") var str=value.split("-") this.a=str[0] this.b=str[1] } } } }) </script> </body>
(2)简写形式
computed:{ //简写,只有get方法 full(){ console.log(' full get被调用了') return this.firstName + '-' + this.lastName } }
二、 侦听器(watch)
1、侦听器
1、当被监视的属性变化时,回调函数自动调用,进行相关操作
2、监视的属性必须存在,才能进行监视,既可以监视 data ,也可以监视计算属性
3、配置项属性 immediate:false ,改为 true,则初始化时调用一次 handler(newValue,oldValue)
4、 监视有两种写法
a、 new Vue时传入watch配置
b.、通过vm.$watch监视
2、基础例子
(1)完整写法
<div id="root"> <h2>今天天气很{{info}}</h2> <button @click="changeWeather">切换天气</button> </div>
const vm = new Vue({ el:'#root', data:{ isHot:true, }, computed:{ info(){ return this.isHot ? '炎热' : '凉爽' } }, methods: { changeWeather(){ this.isHot = !this.isHot } }, //new Vue时传入watch配置 /* watch:{ isHot:{ immediate:true, //初始化时让handler调用一下 //handler什么时候调用?当isHot发生改变时。 handler(newValue,oldValue){ console.log('isHot被修改了',newValue,oldValue) } } } */ }) //通过vm.$watch监视 vm.$watch('isHot',{ immediate:true, //初始化时让handler调用一下 //handler什么时候调用?当isHot发生改变时。 handler(newValue,oldValue){ console.log('isHot被修改了',newValue,oldValue) } })
(2)简写形式
//new Vue时传入watch配置 //简写 isHot(newValue,oldValue){ console.log('isHot被修改了',newValue,oldValue,this) } //通过vm.$watch监视 //简写 vm.$watch('isHot',(newValue,oldValue)=>{ console.log('isHot被修改了',newValue,oldValue,this) }) */
三、 计算属性和侦听器的区别
computed和watch之间的区别:
1、computed能完成的功能,watch都可以完成。
2、watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作。
两个重要的小原则:
1、所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm 或 组件实例对象。
2、所有不被Vue所管理的函数(定时器的回调函数、ajax的回调函数等、Promise的回调函数),最好写成箭头函数,这样this的指向才是vm 或 组件实例对象。