vue 返回当前位置

进入列表页之后,自动请求后台数据,然后点击进入详情页,再返回的时候,想记住上一次列表页的位置,如何实现?

目前遇到了问题:
1:采用哪种方式去实现这个效果
1:从详情页返回列表页的时候,每次都会自动请求数据,导致根本无法记住位置

阅读 5.9k
5 个回答

router.js

// router用history
const appRouter = {
  mode: "history",
  routes: [
    {
      path: "/list",
      name: "list",
      component: List,
      meta: {
        keepAlive: true //不刷新
      }
    }
  ]
}

App.vue入口文件添加keep-alive

<template>
   <div id="app">
      <keep-alive>
         <router-view v-if="$route.meta.keepAlive"></router-view>
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive"></router-view>
   </div>
</template>

我记得上面就可以实现了,如果不可以那把下面加上试试我是这么实现的

router.js主要代码(也可以放到main.js)

import { getScrollTop, setScrollTop } from "@/utils/mixin";
let routerList = [];
router.beforeEach((to, from, next) => {
  //返回上一级浏览位置
  let position = getScrollTop();
  let currentRouterIndex = routerList.findIndex(e => {
    return e.path === from.fullPath;
  });

  if (currentRouterIndex != -1) {
    routerList[currentRouterIndex].position = position;
  } else {
    routerList.push({
      path: from.fullPath,
      position: position
    });
  }
});

router.afterEach((to, from, next) => {

  let savedPosition = routerList.find(e => {
    return e.path === to.fullPath;
  });

  if (typeof savedPosition !== "undefined") {
    Vue.nextTick(() => {
      setScrollTop(savedPosition.position);
    });
  } else {
    Vue.nextTick(() => {
      setScrollTop(0);
    });
  }
});

utils/mixin.js

/*获取到顶部的距离*/
export function getScrollTop() {
  return (
    window.pageYOffset ||
    document.documentElement.scrollTop ||
    document.body.scrollTop
  );
}
/*设置距离*/
export function setScrollTop(value) {
  window.scrollTo(0, value);
}

进入详情页之前存一个sessionStorage作为列表页位置的标识符,初始化列表页的时候取这个session就可以了。

什么叫记不住位置?你用sessionStorage或者vuex都可以记住离开时的位置,进来的时候在请求的回调里面拿这个位置,然后滚动到对应的位置不就可以了。

解决方法主要是记录位置,上面几位都说的很清楚了,如果用的vue-router的话,可以放到meta中记录位置
1、页面离开时

  beforeRouteLeave (to, from, next) {
    // 这里写自己获取的位置
    let position = document.getElementById('vux_view_box_body').scrollTop
    if (to.path === '/home') {
      from.meta.position = 0
    } else {
      from.meta.position = position
    }
    next()
  }

2、回来当前页面,在mounted中$nextTick或setTimeout后scrollTo(0, position)

看到文章说使用keep-alive,应该没问题,但老衲也没用过

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题