VUE hash模式分享/缓存/传参遇到的坑

700 阅读1分钟

1.vue hash模式分享至QQ出现404

原因:QQ不能识别#路由

解决方法: 借用重定向,跳转至指定页面

const routes = [
    {
        path: '*',
        redirect: () => {
            const path = window.location.href;
            // 方法接收 目标路由 作为参数
            // return 重定向的 字符串路径/路径对象
            if(path.includes('index.html') && path.includes('isShare=true')) {
                return { name: 'sharePage', query: qs.parse(path.split('#')[0].split('?')[1]) };
            }
            if(path.includes('index.html') && path.includes('isBanner=true')) {
                return { name: 'BannerPage' };
            }
            return '/Index';
        }
        },
        {
            path: '/Index',
            name: 'Index',
            component: Index,
            meta: {
                keepAlive: true
            }
        },
        {
            path: '/banner',
            name: 'BannerPage',
            component: BannerPage,
            meta: {
                keepAlive: true
            }
        }
  ]

2.vue页面缓存失败, 缓存的页面重新进入不刷新

原因: include的组件必须与组件内name完全相同, 假设退出列表页面,需要清除缓存

* 使用场景:详情页返回列表页不刷新,首页进入其他书籍列表需刷新,  返回列表页、首页需要回到原位置

* 首页 -> 列表页面 -> 详情页

image.png

image.png

image.png

// App.vue
<keep-alive include="Index,PlayList,SleepList,CategoryList">
           <router-view class="child-view" />
</keep-alive>

// 被缓存的组件,根据返回时的路由判断是否清除缓存


beforeRouteLeave(to, from, next) {
       const { parent, key } = this.$vnode;
       const { cache, keys } = parent.componentInstance;
       if(from.name === 'List' && to.name !== 'Detail' && parent && cache) {
       // cache 缓存的组件
       if(cache[key] != null) {
            delete cache[key];
           const index = keys.indexOf(key);
           if(index > -1) {
                 keys.splice(index, 1);
           }
       }
   }

   // tip: 返回即使不重新加载 也会滚动到最顶端,需要记录上次离开时的位置 返回时用scrollTop设置

   this.scroll = this.$refs.page.scrollTop;   

   next();
},

// 页面进入前跳转到上次离开的位置
activated() {
       this.$refs.page.scrollTop = this.scroll;
},

3.vue hash模式路由跳转如果使用this.$route.push({query:  值}) ,设置query中某个字段值为true/false,且会取用判断时,建议使用字符串

原因:原本应取得this.route.query.isDark字段值为true,刷新后this.route.query.isDark字段值为true, 刷新后this.route.query.isDark值会为字符串'true'/'false',如果取值时query.isDark为'false'因为不是空字符串,也会为true, 可以在query设置isDark值时转为字符串, 或者拿到值使用[true, 'true'].includes(isDark)