1、computed
computed主要是针对多对一,也就是多个值的变化会影响一个值的变化,这样的我们就用computed去解决,常用于购物车列表中如下:
我们先学习下vue3种computed的
①函数形式
import {computed,reactive,ref} from "vue"
let price = ref(0);
let goodPrice = computed<string>(()=>{
return `$`+price.value
})
price.value = 500
②对象形式
import {computed,reactive,ref} from "vue"
let data1 = ref(0);
let data2 = ref(0);
const dataNum = computed({
get(){
return data1.value+data2.value
},
set(){
data1.value+data2.value
}
})
2、 watch
watch的第一个参数是侦听源
watch的第二个参数是回调函数cb(newVal,oldVal)
watch的第三个参数是一个options对象{
immediate:true, //是否立即执行
deep:true //是否开启深度监听
}
监听ref的例子:
import {watch.ref} from "vue"
let msg1 = ref<string>('');
let msg2 = ref<string>('');
watch(msg1,(newVal,oldVal)=>{ //这个是监听一个值
console.log(newVal,"新值")
console.log(newVal,"旧值")
})
//如下是监听多个值
watch([msg1,msg2],(newVal,oldVal)=>{ //这个是监听多个值
console.log(newVal,"新值数组")
console.log(newVal,"旧值数组")
})
watch的多个值监听
import {watch.ref} from "vue"
let msg1 = ref({ //这样会新值跟旧值一样用reactive的话就不用使用deep:true
dataObject:{
name:{
age:28
}
}
});
watch(msg1,(newVal,oldVal)=>{ //这个是监听一个值
console.log(newVal,"新值")
console.log(newVal,"旧值")
},{
deep:true, //以上写法用ref的话新值跟旧值是一样的这个是之前的一个bug,目前不知道修复了没有
immediate:true //默认第一次调用下watch
})
//当然如果我们以上的ref换车了reactive的话,watch怎么样都可以监听得到的,无论写不写deep:true
如果我们想要监听对象中的单独属性,不想监听其他值变化怎么办?
import {watch.reactive} from "vue"
let person = reactive({ //这样会新值跟旧值一样用reactive的话就不用使用deep:true
name:"axin",
height:"178",
weight:"76公斤"
});
watch(()=>person.height,(newVal,oldVal)=>{ //这个是监听单一的值
console.log(newVal,"新值")
console.log(newVal,"旧值")
},{