vue中computed,methods,watch简单理解
computed和method都能实现同一个功能的时候,建议使用computed,因为computed有缓存
computed和watch都能实现同一个功能的时候,建议使用computed,因为更加简洁
computed:计算属性
computed是基于它的依赖缓存,只有相关依赖发生改变时才会重新取值
methods:方法
methods在页面重新渲染的时候,函数总会重新调用执行
watch:侦听器
可以监听data数据属性的改变,并且做一些异步操作;如:price();
可以监听获取data数据的新值,旧值;如:count(newValue, oldValue)
watch: {
price() {
setTimeout(function() {
console.log("监听price数据的改变,并且3秒后输出console")
}, 3000);
},
count(newValue, oldValue) {
//newValue:新修改的值;oldValue:原来的旧值
console.log(newValue, oldValue)
}
}
computed和methods的区别:
1.computed是属性调用,而methods是函数调用;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="root">
</div>
</body>
<script src="https://unpkg.com/vue@next"></script>
<script>
const app = Vue.createApp({
data() {
return {
count: 2,
price: 10,
}
},
computed: {
//当计算属性依赖的内容发生变更时,才会重新执行计算
total() {
return this.count * this.price;
}
},
methods: {
//只要页面重新渲染,才会重新计算
getTotal() {
return this.count * this.price;
}
},
template: `
<div>computed:{{total}}-methods:{{getTotal()}}</div>
`
})
const vm = app.mount("#root");
</script>
</html>
2.computed带有缓存功能,而methods不是