业务需求
从A页面传参跳转B页面,B页面传参跳转C页面,C页面可以返回B页面
遇到问题
当C页面返回B页面时,由于B页面参数丢失导致页面渲染失败
解决方案
利用localStorage
思路:把B页面拿到的参数啊也传给C页面,在C页面把数据存储在localStorage中,返回B页面判断有无,再从storage中取出
// A页面
linkToDetail(id?: string, sheetSize?: number) {
this.$router.push({
name: 'B',
query: {
id: id + '',
},
});
}
// B页面
// 判断数据源来源
async created() {
if (this.$route.query.id) {
this.id = this.$route.query.id;
} else {
const statisticsAnalyzeParams = localStorage.getItem(
'statisticsAnalyzeParams',
);
this.id = JSON.parse(statisticsAnalyzeParams).id;
}
await this.getPageStatistics({ id: this.id });
}
linkToDetail(id: any) {
this.$router.push({
name: 'C',
params: {
pageId: this.id + '',
},
});
}
// C页面
beforeRouteLeave(to: any, from: any, next: any) {
const tranferParams = {
id: this.$route.params.pageId,
};
localStorage.setItem(
'statisticsAnalyzeParams',
JSON.stringify(tranferParams),
);
next();
}
使用keep-alive
<keep-alive>
<router-view v-if="$route.meta.keepAlive">
<!-- 这里是会被缓存的视图组件! -->
</router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive">
<!-- 这里是不被缓存的视图组件! -->
</router-view>
// 路由文件
{
path:'/index',
name:'B',
component:index,
meta: {
keepAlive: true // 需要被缓存
}
},