1.直接上踩坑前的代码
import type { ImgType } from '@/type'
import { reactive, watch } from 'vue'
// 收藏夹中的数据
export const useFavorites = reactive<Array<ImgType>>([])
watch(() => useFavorites, () => {
console.log('useFavorites触发了更新')
})
/**
* 更新收藏夹
* @param type [STRING] 添加|删除
* @param img 图片对象信息
*/
export const updateFavorites = (type: string, img: ImgType) => {
if (type === 'add') {
useFavorites.push(img)
} else {
useFavorites.forEach((item: ImgType, index: number) => {
if (item.url === img.url) return useFavorites.splice(index, 1)
})
}
}
使用 watch 监听 useFavorites 值的变化时,却发现当修改了useFavorites 数组中的成员是,watch内的打印信息并没有触发。那么为什么呢?于是翻阅了vue的官方文档,发现 watch 默认不会触发深度监视。也就是说,如果你想监视嵌套数据的变化,需要设置 deep:true。
2.添加深度监视配置项
watch(() => useFavorites, () => {
// 书写触发更新后的统一罗辑
}, { deep: true })