vue computed

78 阅读1分钟

概念理解

类型

{ [key: string]: Function | { get: Function, set: Function } }

详细

属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。

注意如果你为一个计算属性使用了箭头函数,则 this 不会指向这个组件的实例,不过你仍然可以将其实例作为函数的第一个参数来访问。

例子

computed: {
  aDouble: vm => vm.a * 2
}

computed: {
	
    get(){
		return this.xxxx;
	
    }

}

computed: {
	value: {
		get(){
			return this.xxxx;		
		},
		set(val){
			this.$emit()
		}
	}
	

}

注意:计算属性的结果会被缓存,除非依赖的响应式 property 变化才会重新计算。注意,如果某个依赖 (比如非响应式 property) 在该实例范畴之外,则计算属性是不会被更新的。

注意点一

computed中定义的一个变量没有在相关属性发生变化后触发更新。

例子如下

当调用changeAge设置person年龄之后,调用this.personAge 发现personAge值为undefined,

person 中 的age 并不是响应是的,

data(){
	return {
		person:{
			name:"小虽"
		}
	}
}

computed:{
	personAge(){
		return this.person.age;
	}
}

method:{
	changeAge(){
		this.person.age = 24;
	}
}

修改

data(){
	return {
		person:{
			name:"小虽",
            age: 0
		}
	}
}

computed:{
	personAge(){
		return this.person.age;
	}
}

method:{
	changeAge(){
		this.person.age = 24;
	}
}

注意点二

局部变量:在获取值的时候尽量设置参数,

// 优化
 computed: {
    res({ start, count}) { 
        return start + count;
    }
  }


// 无优化
 computed: {
    res() { 
        return this.start + this.count;
    }
  }

计算前先用局部变量 start, count,缓存起来,后面直接访问。
优化前后的组件的计算属性 res 的实现差异,优化前的组件多次在计算过程中访问this.{ start, count}

原因是你每次访问 this.xx 的时候,由于 this.{ start, count}是一个响应式,会触发getter,进而会执行依赖收集相关逻辑代码。这也算是性能优化技巧吧,在this.xxx 访问次数比较多的时候。