当前位置: 代码迷 >> 综合 >> vue2 中使用keep-alive
  详细解决方案

vue2 中使用keep-alive

热度:55   发布时间:2024-01-12 18:27:13.0

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!