session存储数据-解决歌手页面刷新报错的问题

发布时间 2023-09-17 11:33:07作者: Ly021

刷新报错的原因是,singer数据是需要在singer.vue页面去传到singerdetail.vue页面的,所以想要重新加载singerdetail页面就必须重新返回到singer页面,很麻烦,想要解决就只需要将数据存储到session中既可以,网站的数据存储一般有两种,一个是location一个是session,这里的话不用用到location,用session这种短暂的会话存储就好,location是本地存储,相对来说没必要,session已经足够

步骤:在singer-detail中定义钩子函数

computedSinger() {
        let ret = null
        const singer = this.singer
        if (singer) {
          ret = singer
        } else {
          const cachedSinger = storage.session.get(SINGER_KEY)
          if (cachedSinger && cachedSinger.mid === this.$route.params.id) {
            ret = cachedSinger
          }
        }
        return ret
      }
在singer和singerdetail中导入storage方法,在constant.js中定义共享常量
在singer中定义cacheStorage方法
cacheStorage(singer) {
        storage.session.set(SINGER_KEY, singer)
      }
最后注意设置一层过滤防止地址栏改变时出错
if (!this.computedSinger) { // 避免修改地址栏导致获取不到对于的id值,做一个过滤,使得回到上一级路由,显得合理
        const path = this.$route.matched[0].path
        this.$router.push({
          path
        })
        return
      }