vue-router学习(二) --- 常用功能

命名路由

对路由设置name属性,为了方便路由的跳转,如果单纯的通过path跳转,一旦path的值过长,或者路由嵌套很深,会显的很乱维护也比较麻烦。

const routes:Array<RouteRecordRaw> = [
    {
        path:"/",
        name:"Login",
        component:()=> import('../components/login.vue')
    },
    {
        path:"/reg",
        name:"Reg",
        component:()=> import('../components/reg.vue')
    }
]

router-link跳转方式需要改变 变为对象并且有对应name

    <div>
      <router-link :to="{name:'Login'}">Login</router-link>
      <router-link style="margin-left:10px" :to="{name:'Reg'}">Reg</router-link>
    </div>
    <hr />

编程式导航

不使用router-link,直接使用router实例操作路由

import { useRouter } from 'vue-router'
const router = useRouter()
 
字符串形式直接填写path地址
const toPage = () => {
  router.push('/reg')
}

对象形式
const toPage = () => {
  router.push({
    path: '/reg'
  })
}


命名路由形式
const toPage = () => {
  router.push({
    name: 'Reg'
  })
}

路由传参

我们说下对象形式路由传参的注意点:

  1. path只能和query连用
  2. name只能和params连用

如果提供了 pathparams 会被忽略(因为path是死路经,params是动态路径,query只是路径后的参数),上述例子中的 query 并不属于这种情况。

params传参是不会显示在路径上的(query会显示),缺点是params是存在内存中的,刷新页面就会消失。可以配合动态路由一起用刷新就不会消失了(/user/:id

// 字符串
router.push('home')

// 对象
router.push({ path: '/home' })

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

// 带查询参数,变成 /register?plan=private
router.push({ path: '/register', query: { plan: 'private' }})

路由接收参数

import { useRoute } from 'vue-router';
const route = useRoute()
console.log(route.query)
console.log(route.params)

动态路由传参

const routes:Array<RouteRecordRaw> = [
    {
        path:"/",
        name:"Login",
        component:()=> import('../components/login.vue')
    },
    {
        动态路由参数
        path:"/reg/:id",
        name:"Reg",
        component:()=> import('../components/reg.vue')
    }
]
const toDetail = (item: Item) => {
    router.push({
        name: 'Reg',
        params: {
            id: item.id
        }
    })
}

嵌套路由

一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构,例如:

const routes: Array<RouteRecordRaw> = [
    {
        path: "/user",
        component: () => import('../components/footer.vue'),
        children: [
            {
                path: "",
                name: "Login",
                component: () => import('../components/login.vue')
            },
            {
                path: "reg",
                name: "Reg",
                component: () => import('../components/reg.vue')
            }
        ]
    },
 
]
    <div>
        <div>
            <router-link to="/">login</router-link>
            <router-link style="margin-left:10px;" to="/user/reg">reg</router-link>
        </div>
        <router-view></router-view>
    </div>

children 配置只是另一个路由数组,就像 routes 本身一样。因此,你可以根据自己的需要,不断地嵌套视图

不要忘记写router-view,嵌套路由需要在指定位置配置router-view,否则内容也不会显示


命名视图

命名视图可以在同一级(同一个组件)中展示更多的路由视图,而不是嵌套显示。

命名视图可以让一个组件中具有多个路由渲染出口,这对于一些特定的布局组件非常有用。

命名视图的概念非常类似于“具名插槽”,并且视图的默认名称也是 default

确保正确使用 components 配置 (带上 s)

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
 
 
const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        components: {
            default: () => import('../components/layout/menu.vue'),
            header: () => import('../components/layout/header.vue'),
            content: () => import('../components/layout/content.vue'),
        }
    },
]
 
const router = createRouter({
    history: createWebHistory(),
    routes
})
 
export default router
<div>
    <router-view></router-view>
    <router-view name="header"></router-view>
    <router-view name="content"></router-view>
</div>

重定向、别名、返回

重定向

1.字符串形式

直接填写path地址即可

const routes: Array<RouteRecordRaw> = [
    {
        path:'/',
        component:()=> import('../components/root.vue'),
        redirect:'/user1',
    }
]

2.对象形式

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        component: () => import('../components/root.vue'),
        redirect: { path: '/user1' },
    }
]

3.函数模式(可以传参)

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        component: () => import('../components/root.vue'),
        redirect: (to) => {
        方法接收目标路由作为参数
            return {
                path: '/user1',
                query: to.query
            }
        }
    }
]

注意:如果做路由拦截 beforeRouterEnter拦截的是最终的路径地址而不是重定向之前的


别名

/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。

const routes: Array<RouteRecordRaw> = [
    {
        path: '/a',
        component: () => import('../components/a.vue'),
        alias: '/b'
        也可以配置为数组 匹配任意值都是当前的
        alias:['/c','/d','/e']
    }
]

返回

const next = () => {
  前进 数量不限于1
  router.go(1)
}
 
const prev = () => {
  后退
  router.back()
}

路由元信息

通过路由记录的 meta 属性可以定义路由的元信息。使用路由元信息可以在路由中附加自定义的数据,例如:

  • 权限校验标识。
  • 路由组件的过渡名称。
  • 路由组件持久化缓存 (keep-alive) 的相关配置。
  • 标题名称

我们可以在导航守卫或者是路由对象中访问路由的元信息数据。

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Login.vue'),
      meta: {
        title: "登录"
      }
    },
    {
      path: '/index',
      component: () => import('@/views/Index.vue'),
      meta: {
        title: "首页",
      }
    }
  ]
})

如果不使用扩展 TS将会是unknow 类型

declare module 'vue-router' {
  interface RouteMeta {
    title?: string
  }
}
router.beforeEach((to, from, next) => {
	document.title = to.meta.title
    next()
})

滚动行为

使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。vue-router 可以自定义路由切换时页面如何滚动。

当创建一个 Router 实例,你可以提供一个 scrollBehavior 方法

const router = createRouter({
  history: createWebHistory(),
  scrollBehavior: (to, from, savePosition) => {
    return {
       top:200
    }
  },
const router = createRouter({
  history: createWebHistory(),
  scrollBehavior: (to, from, savePosition) => {
    console.log(to, '==============>', savePosition);
    return new Promise((r) => {
      setTimeout(() => {
        r({
          top: 10000
        })
      }, 2000);
    })
  },

scrollBehavior 方法接收 tofrom 路由对象。第三个参数 savedPosition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值