1.适用于任何复杂逻辑,你都应当使用计算属性。
2.computed 和methods的不同;
如果你想要缓存的话,就使用computed
3.computed和watch的不同:
当需要在数据变化时执行异步或开销较大的操作时,建议使用watch;
template:
<button @click="transform">改变</button>
{{haha}}
js:
data(){
return{
msg: 2,
num: 4
}
}
computed: {
haha: {
get() {
console.log('get方法执行了');
return this.msg + ', ' + this.num;
},
set(newValue) {
console.log('set方法执行了')
this.msg = 4 + newValue
}
},
},
methods: {
transform(){
this.haha = '你好';
},
}
先执行的是get方法:只有计算对象的值改变了,然后才会执行set方法; 然后最后在执行get方法;
watch的一些用法:
template:
<input v-model="changeValue">
js:
data() {
return{
changeValue: '2121'
}
},
created() {
this.getAlert();
},
methods: {
getAlert(){
this.haha = '你好';
},
watch: {
changeValue(){
this.getAlert();
}
}
这是常规写法
优化:
watch: {
changeValue: {
handler: 'getAlert', // 可以直接写函数的自变量名称
immediate: true // 表示创建组件时立马执行一次
},
}
watch的其他的api (对象 ,数组) 深度检测和字符串形式监听
data() {
return{
changeValue:{
aa: '1212'
},
}
},
watch: {
changeValue:{
handler: 'getAlert',
deep: true, // 深度检测
immediate: true
}
第二种方法:
watch: {
'changeValue.aa':{
handler: 'getAlert',
// handler(newN,old) { 有时候需要获取变化的值
// console.log(newN,old)
// },
immediate: true,
}
}
};