Vuex page implements caching between multiple page jumps

Example description:
Now there is a main page called home, another page called music list page (qq-music), and the remaining page is called music detail page (qq-music-detail),
now we use vuex to realize from the home page When you go to the music list page, go from the music list to the music details page.
1. If you return to the music list page from the music details page, you need to display the data of the last time you entered the music list page.
2. If you enter the music list page from the home page, re-request without loading cached data
How to cache data with vuex in the previous article

On the basis of the implemented cache, the problem to be solved now is how to clear the cached data when entering the music list page from the home page. If it is unclear, no matter which page is entered from, the cached data will always be there.
At this time, a routing function beforeRouteEnter is mainly used, and a meta tag should be added when routing configuration to distinguish whether to enter from the previous page or return from the next page.
The routing configuration is as follows:

    {
    
    
        id: 1113,
        meta: {
    
    
          title: "0219",
          isBack: false,
        },
        path: "/0219",
        component: QqMusic,
      },

The beforeRouteEnter function is used as follows:

  // 如果是从音乐详情页面过来的话,就把目标页面的isBack改为true
  beforeRouteEnter(to, from, next) {
    
    
    if (from.name === "QqMusicDetail") {
    
    
      to.meta.isBack = true;
    }
    next();
  },

The empty data in created is as follows:

// 取反可以判断出页面是否需要缓存
    if (!this.$route.meta.isBack) {
    
    
      // 清空缓存的数据
      this.updateActiveName(null);
      this.updateCacheMusicList(null);
    }
    this.$route.meta.isBack = false; // 状态再进行重置

The code of vuex–>music.js is as follows: mainly to change the state change of the cached data in the state

state:{
    
    
	cacheMusicList: {
    
    }, // 测试缓存的musiclist
    activeName: "", // 当前选中的歌手名字
},
mutations:{
    
    
    // 根据条件更新缓存music,有则用,无则更新
    updateCacheMusicList(state, payload) {
    
    
      if (payload !== null) {
    
    
        state.cacheMusicList[payload?.k] = payload?.v;
        state.cacheMusicList = JSON.parse(JSON.stringify(state.cacheMusicList));
      } else {
    
    
        state.cacheMusicList = {
    
    };
      }
    },
    // 更新当前选中的name
    updateActiveName(state, payload) {
    
    
      state.activeName = payload;
    },
}

Guess you like

Origin blog.csdn.net/qq_45989814/article/details/123122571