计算属性 computed
被计算出来的属性,我们称之为计算属性,依赖于缓存,只有当缓存变化的时候,才会重新计算,详细来说就是,页面如果重新渲染,但是 data 中的数据的值没有发生改变,计算属性会立刻返回之前的计算结果,而不会再次执行函数
<template>
<div id="app">
<button @click="getNewDate">newDate</button>
</div>
</template>
<script>
export default {
computed:{
newDate(){
return new Date().getSeconds().toString()
}
},
methods: {
getNewDate(){
console.log(this.newDate)
}
}
};
</script>
侦听属性 watch
当数据变化时,执行一个函数,我们称之为侦听属性,监听 props ,执行$emit和本组件的值时为异步操作。无缓存性,页面渲染时,值不变化也会执行函数。
<template>
<div id="app">
{{n}}
<hr />
<button @click="add">+1</button>
<hr/>
<button @click="undo">撤销</button>
<hr/>
{{history}}
</div>
</template>
<script>
export default {
data:{
n:0,
history: [],
inUndoMode:false
},
methods:{
add(){
this.n+=1
},
undo(){
const last = this.history.pop();
this.inUndoMode = true;
const old = last.from;
this.n = old;
this.$nextTick(() => {
this.inUndoMode = false;
});
}
},
watch:{
n(newValue,oldValue){
if (!this.inUndoMode) {
this.history.push({ from:oldValue, to: newValue });
}
}
}
};
</script>
在 watch中,还有以下的属性:
- immediate为true时则立即触发回调函数;如果为false,不会立即执行回调。
- deep为深入监听,是在对象中层层遍历,并在监听对象上的每一个属性上都添加监听。
computed 和 watch 的区别
computed是计算属性,watch是侦听属性computed依赖缓存,当页面重新渲染但数据的值没有改变时,不执行函数computed适合多个数据变化影响一个数据,watch适合一个数据的变动影响多个数据或者复杂的运算
总结
- 如果一个数据需要经过复杂计算就用 computed
- 如果一个数据需要被监听并且对数据做一些操作就用 watch