vue-router嵌套路由切换外层路由时不改变内层路由的定位状态

案例中的路由映射代码

const routes = [
  {
     
    path: '/',
    redirect: '/home'
  },
  {
     
    path: '/home',
    component: () => import('./../components/Home'),
    meta: {
     
      title: 'home'
    },
    children: [
      {
     
        path: 'message',
        component: () => import('./../components/HomeMessage')
      },
      {
     
        path: 'new',
        component: () => import('./../components/HomeNew')
      }
    ]
  },
  {
     
    path: '/about',
    meta: {
     
      title: 'about'
    },
    component: () => import('./../components/About')
  },
  {
     
    path: '/user',
    meta: {
     
      title: 'user'
    },
    component: () => import('./../components/User')
  }
]

主要包含三个路由:home、about、user,其中home中又嵌套着两个路由:message、new

需求:当从/home/new或者是/home/message页面切换到/about或者/user之后,再从该页面切换回/home之后,依然保持为切换之前的/home/new或/home/message页面
效果如图所示:
vue-router嵌套路由切换外层路由时不改变内层路由的定位状态_第1张图片
Home组件中具体代码:

<template>
  <div>
    <p>首页页面p>
    <p>首页页面的内容p>
    <router-link to="/home/message">信息router-link>
    |
    <router-link to="/home/new">新闻router-link>
    <router-view>router-view>
  div>
template>

<script>
  export default {
      
    name: 'Home',
    data() {
      
      return {
      
        path: '/home/message'
      }
    },
    activated() {
      
      this.$router.push(this.path)
    },
    // 通过组件内部的导航守卫实现
    beforeRouteLeave(to, from, next) {
      
      // this.path = this.$route.path
      this.path = from.path
      next()
    }
  }
script>

<style scoped>

style>

你可能感兴趣的:(vue,vue)