Vue:在路由跳转过程中记住滚动条的位置

长列表滚动后,路由切换回来要让滚动条在离开时的位置

使用路由的缓存和vuex来实现

  1. 在需要记住进度条的页面
// .test-view-wrapper 是出现滚动条的元素
activated() {
  // 组件在前台显示时设置进度条的位置
  document
    .querySelector(".test-view-wrapper")
    .scrollTo(0, this.$store.state.scrollPosition);
},
beforeRouteLeave(to, from, next) {
  // 将离开时进度条的位置进行记录
  let p = document.querySelector(".test-view-wrapper").scrollTop;
  this.$store.commit("scrollPosition", p);
  next();
},
  1. 路由的缓存
<template>
  <div id="app">
    <keep-alive>
      <router-view>router-view>
    keep-alive>
  div>
template>
  1. vuex
state: {
  scrollPosition: 0,
},
mutations: {
  scrollPosition(state, position) {
    state.scrollPosition = position;
  },
},

你可能感兴趣的:(记录,vue.js,前端,javascript)