vue2项目中使用keep-alive,可在路由跳回该组件时展示跳走前的数据形式,滚动条等。

步骤1:在route.js中使用keepAlive属性,并且定义一个scrollTop存储滚动条位置

{
    path: "/check/list",
    name: "CheckList",
    component: CheckList,
    meta: {
      title: "审核列表",
      keepAlive: true,
      scrollTop: 0
    }
  }

步骤2:在App.vue中将使用keepAlive的组件进行包裹

<keep-alive>
  <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-else></router-view>

步骤3,具体使用keepAlive属性的组件中

export default {
  name: "CheckList",//这里与keepAlive属性的路由名字统一
  activated() {
    const scrollTop = this.$route.meta.scrollTop;
    const ele = document.querySelector("#listWrap");//有滚动条的元素,别找错了
    if (scrollTop) {
      ele.scrollTop = scrollTop;
    }
  },
  beforeRouteLeave(to, from, next) {
    const ele = document.querySelector("#listWrap");
    const scrollTop = ele ? ele.scrollTop : 0;
    from.meta.scrollTop = scrollTop;
    next();
  }

over!

Logo

前往低代码交流专区

更多推荐