vue-计算属性
1.定义
要用的属性不存在,要通过已有属性计算得来。
2.原理
底层借助了Object.defineproperty方法提供的getter和setter。
3.get函数什么时候执行
(1)初次读取时会执行一次。
(2)当依赖的数据发生改变时会被再次调用
4.优势
与methods实现相比,内部有缓存机制(复用)。效率更高,调试方便。
5.备注
- 计算属性最终会出现在vm上,直接读取使用即可。
- 如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。
6.实例
computed:{
get(){
// get有什么作用当有人读取fullName时,get就会被调用,且返回值作为fullName的值
// get什么时候调用?1.初次读取fullNmae时。2.所依赖的数据发生变化时。
console.log('get被调用了');
return this.xxx + '-' + this.xxxxx
},
// set什么时候调用?当fullName被修改时
set(value){
console.log('set',value)
const arr = value.split('-');
this.firstName = arr[0];
this.lastName = arr[1];
}
}
7.拓展(计算属性传参)
entrustTime: () => {
return (time) => {
return (time + '').substr(0, 4) + '年' + (time + '').substr(4, 2) + '月' + (time + '').substr(6, 2) + '日'
}
}