uni-app 返回上一级页面时页面数据丢失(不是页面空白)
uni-app 返回上一级页面时页面数据丢失(不是页面空白)
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | Windows 10 专业版/20H2/19042.804 | HBuilderX |
操作步骤:
- 进入首页
- 从首页index跳转到list页面
- list页面刷新
- 返回到首页
- 首页数据没了
预期结果:
首页有数据
实际结果:
没有数据了
bug描述:
H5调试:首页index跳转到list页面,然后在list页面刷新,再返回index页面,index的数据就没有了。
更多关于uni-app 返回上一级页面时页面数据丢失(不是页面空白)的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复
更多关于uni-app 返回上一级页面时页面数据丢失(不是页面空白)的实战教程也可以访问 https://www.itying.com/category-93-b0.html
这个问题通常是由于页面生命周期管理不当导致的。当从列表页刷新后返回首页时,首页组件被重新初始化,但数据没有正确恢复。
解决方案:
- 使用全局状态管理(推荐)
// store/index.js
export const store = {
state: {
homeData: null
},
setHomeData(data) {
this.state.homeData = data
}
}
// index.vue
import { store } from '@/store'
export default {
onLoad() {
if (store.state.homeData) {
this.dataList = store.state.homeData
} else {
// 首次加载请求数据
this.fetchData()
}
},
methods: {
fetchData() {
// 获取数据后保存到全局状态
store.setHomeData(yourData)
}
}
}
- 使用页面栈缓存
// index.vue
export default {
onHide() {
// 页面隐藏时缓存数据
uni.setStorageSync('homeData', this.dataList)
},
onShow() {
// 页面显示时恢复数据
const cachedData = uni.getStorageSync('homeData')
if (cachedData) {
this.dataList = cachedData
}
}
}
- 使用uni-app的页面通信
// list.vue
uni.$emit('refreshHome', newData)
// index.vue
export default {
onLoad() {
uni.$on('refreshHome', (data) => {
this.dataList = data
})
},
onUnload() {
uni.$off('refreshHome')
}
}