Vue3:返回组件(运用keepAlive保留滚动位置)

this.$router.go(-1) ( VUE3写法 :proxy.$router.go(-1) )返回上一页最简单实用,现通过路由传参及keepAlive,实现返回保留滚动条位置

router.js

注:需要保留滚动条的页设置keepAlive: true

import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('@/views/index.vue'),
  }, {
    path: '/rule',
    name: 'rule',
    component: () => import('@/views/rule.vue'),
  },{
    path: '/list',
    name: 'list',
    component: () => import('@/views/list.vue'),
    meta: {
      keepAlive: true // 需要缓存
    }
  }, {
    path: '/about/:orderid',
    name: 'about',
    component: () => import('@/views/about.vue')
  }, {
    path: '/rank',
    name: 'rank',
    component: () => import('@/views/rank.vue'),
    meta: {
      keepAlive: true // 需要缓存
    }
  }
]

//history模式对应createWebHistory()方法
//hash模式对应createWebHashHistory()方法
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

App.vue



需保存滚动条位置页.vue

注意这两个onActivatedonDeactivated 这两个生命周期钩子函数,

需要import {onActivated,onDeactivated} from 'vue'



返回组件使用页.vue



GoBack返回组件



GoTop回顶部组件



你可能感兴趣的:(Millia's,work,html,前端)