计算属性compute作用:
和普通属性一样在模板中使用计算属性,当data中对应的数值发生变化时,计算属性的值会发生相应的变化,计算属性compute是基于他们的依赖(如果是实例范畴之外的依赖,比如非响应式的notreactive是不会触发属性更新的)进行存储(计算属性的结果会被存储)。只有相关依赖发生改变时才会重新求值,未改变只会返回之前的结果,不在执行函数。
示例代码
html
<div id="app">
<p>{{firstName}}</p>
<p>{{lastName}}</p>
<p>{{fullName}}</p>
<p>{{otherName}}</p>
</div>
js
let vm = new Vue({
el : "#app",
data : function (){
return {
firstName : "Gavin",
lastName : "CLY",
}
},
computed : {
fullName : function () {
console.log(this);
return this.firstName + this.lastName
},
/* 不可使用箭头函数 */
otherName : ()=>{
/* this 指向window */
console.log('箭头函数',this);
let that = this;
return that.firstName + that.lastName
}
}
})
执行结果
结论
此时箭头函数的this执行发生变化(指向window),因为箭头函数绑定了父级作用域的上下文,所以this将不会按照期望指向vue(此时vue指向window)