相同点
- 都是函数,都可以插值到 DOM 中,并且是响应式
平时很少或基本不会在项目中使用 methods 中的方法执行插值的方式,也不推荐,但还是要了解可以这么做,以及为什么不这么做的原因。
<template>
<div>
<div>{{ fullName }}</div>
<div>{{ getFullName() }}</div>
<button @click="changeName()">改变lastName</button>
</div>
</template>
<script>
export default {
data(){
return {
firstName:"zhang",
lastName:"jack"
}
},
computed:{
fullName(){
console.log('computed call')
return this.firstName + this.lastName;
}
},
methods:{
getFullName(){
console.log('method call')
return this.firstName + this.lastName;
},
changeName(){
this.lastName = "tom"
}
}
}
</script>
以上,两种不同方式的插值,在 DOM 展示上的没有任何差异。打印也是 computed call
和 method call
各一次。
再说,响应数据的变化的表现,在点击按钮的触发改变 lastName 的值,computed 中的 fullName 函数和 methods 中的 getFullName 都被触发。
不同点
- computed 中的插值时,不需要调用执行,而 method 中的需要执行。
- 同一个 Vue 实例中, computed 可以复用已经计算出的值,而 methods 中的却需要每次都执行,在数据变化的时候,也是 computed 只执行一遍,而 methods 中的
getFullName
调用却要调用多次执行。
稍微改变一下,即 DOM 中多处插入相同的值时,如下:
<template>
<div>
<div>{{ fullName }}</div>
<div>{{ fullName }}</div>
<div>{{ fullName }}</div>
<div>{{ getFullName() }}</div>
<div>{{ getFullName() }}</div>
<div>{{ getFullName() }}</div>
<button @click="changeName()">改变lastName</button>
</div>
</template>
<script>
export default {
data(){
return {
firstName:"zhang",
lastName:"jack"
}
},
computed:{
fullName(){
console.log('computed call')
return this.firstName + this.lastName;
}
},
methods:{
getFullName(){
console.log('method call')
return this.firstName + this.lastName;
},
changeName(){
this.lastName = "tom"
}
}
}
</script>
以上,打印了一次 computed call
,却打印了三次 method call
,很显然,methods 中的方法插值,每一次都是需要执行一次函数的,而 computed 则能够复用之前已经计算的值。
剖析
那么问题来了,是什么造成了 computed 和 methods 上的同样作为方法,却一个需要带上()执行,另一个不需要。又为何 computed 上的返回值实现了复用,而 methods 上的却没有。内在到底进行了怎么的不公正待遇。
挖坑,有空再分解。