vue复杂数据类型多层嵌套的监听
本来看前辈的做法是watch的嵌套,遇到这种复杂的数据结构还是不多,分享一下前辈的做法
let stopChildWatchList = [] // 用于存放每个子监听器watch(() => data,(val) => {// 清除旧监听stopChildWatchList.forEach(stop => stop())stopChildWatchList = []val.forEach((item, i) => {item.children.forEach((child, j) => {const stop = watch(() => child.tags,(newTags) => {console.log(`data[${i}].children[${j}].tags changed:`, newTags)},{ deep: true })stopChildWatchList.push(stop)})})},{ deep: true, immediate: true }
)
后面我感觉有点不太好读,就去找了一下另一种做法,比较易懂,给自己做个记号
watch(() =>data.flatMap(item =>item.children.flatMap(child => [...child.tags])),(newVal) => {console.log('所有 tags 改了:', newVal)}
)