Vue.js watch 函数中获取数据并使用
如何在其他函数中使用 Vue.js watch 函数的 newValue
您可以将 watch 的回调函数中的 newValue 保存到一个变量中,然后在其他函数中使用该变量。例如:
let currentPhotoInfoArr = [];
watch(photoInfoArr, (newValue, oldValue) => {
console.log('photoInfoArr发生了改变!!!', newValue, oldValue);
currentPhotoInfoArr = newValue; // 将 newValue 保存到 currentPhotoInfoArr 变量中
}, {
immediate: true,
deep: true
});
function otherFunction() {
console.log(currentPhotoInfoArr); // 在其他函数中使用 currentPhotoInfoArr 变量
}
解释:
- 声明变量: 在 watch 函数外部声明一个变量
currentPhotoInfoArr,用于存储最新的newValue。 - 保存 newValue: 在 watch 的回调函数中,将
newValue赋值给currentPhotoInfoArr变量。 - 其他函数使用: 在其他函数 (如
otherFunction) 中,直接使用currentPhotoInfoArr变量即可获取最新数据。
原文地址: https://www.cveoy.top/t/topic/nsIB 著作权归作者所有。请勿转载和采集!