鍍金池/ 問答/HTML/ vue 返回當(dāng)前位置

vue 返回當(dāng)前位置

進(jìn)入列表頁(yè)之后,自動(dòng)請(qǐng)求后臺(tái)數(shù)據(jù),然后點(diǎn)擊進(jìn)入詳情頁(yè),再返回的時(shí)候,想記住上一次列表頁(yè)的位置,如何實(shí)現(xiàn)?

目前遇到了問題:
1:采用哪種方式去實(shí)現(xiàn)這個(gè)效果
1:從詳情頁(yè)返回列表頁(yè)的時(shí)候,每次都會(huì)自動(dòng)請(qǐng)求數(shù)據(jù),導(dǎo)致根本無(wú)法記住位置

回答
編輯回答
我不懂

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>

我記得上面就可以實(shí)現(xiàn)了,如果不可以那把下面加上試試我是這么實(shí)現(xiàn)的

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

import { getScrollTop, setScrollTop } from "@/utils/mixin";
let routerList = [];
router.beforeEach((to, from, next) => {
  //返回上一級(jí)瀏覽位置
  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
  );
}
/*設(shè)置距離*/
export function setScrollTop(value) {
  window.scrollTo(0, value);
}
2017年12月17日 13:53
編輯回答
吃藕丑

什么叫記不住位置?你用sessionStorage或者vuex都可以記住離開時(shí)的位置,進(jìn)來(lái)的時(shí)候在請(qǐng)求的回調(diào)里面拿這個(gè)位置,然后滾動(dòng)到對(duì)應(yīng)的位置不就可以了。

2017年1月12日 12:28
編輯回答
逗婦惱

看到文章說使用keep-alive,應(yīng)該沒問題,但老衲也沒用過

2018年7月8日 07:46
編輯回答
扯機(jī)薄

解決方法主要是記錄位置,上面幾位都說的很清楚了,如果用的vue-router的話,可以放到meta中記錄位置
1、頁(yè)面離開時(shí)

  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、回來(lái)當(dāng)前頁(yè)面,在mounted中$nextTick或setTimeout后scrollTo(0, position)

2018年2月27日 00:06
編輯回答
扯不斷

進(jìn)入詳情頁(yè)之前存一個(gè)sessionStorage作為列表頁(yè)位置的標(biāo)識(shí)符,初始化列表頁(yè)的時(shí)候取這個(gè)session就可以了。

2017年5月30日 05:37