• Vue Router


    0 路由原理

    路由器的两种工作模式:

    hash模式:(toB)

            地址中永远带着#号,不美观,兼容性较好(#及其后面的内容就是hash值,hash值不会带给服务器);

            若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。

    history模式:(toC)

            兼容性较差;路径会提交给后台。

            应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。

    hash :window.onhashchange监听路由改变。

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>hash testtitle>
    8. head>
    9. <body>
    10. <p>hash testp>
    11. <button id="btn1">修改 hashbutton>
    12. <script>
    13. //3. hash 变化,包括:
    14. // a. JS 修改 url
    15. // b. 手动修改 url 的 hash
    16. // c. 浏览器前进、后退
    17. window.onhashchange = (event) => {
    18. console.log('old url', event.oldURL)
    19. console.log('new url', event.newURL)
    20. console.log('hash:', location.hash)
    21. }
    22. //1. 页面初次加载,获取 hash
    23. document.addEventListener('DOMContentLoaded', () => {
    24. console.log('hash:', location.hash)
    25. })
    26. //2. JS 修改 url
    27. document.getElementById('btn1').addEventListener('click', () => {
    28. location.href = '#/user'
    29. })
    30. script>
    31. body>
    32. html>

     history:window.onpopstate监听路由改变。

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>history API testtitle>
    8. head>
    9. <body>
    10. <p>history API testp>
    11. <button id="btn1">修改 urlbutton>
    12. <script>
    13. //1. 页面初次加载,获取 path
    14. document.addEventListener('DOMContentLoaded', () => {
    15. console.log('load', location.pathname)
    16. })
    17. //2. 打开一个新的路由
    18. // 【注意】用 pushState 方式,浏览器不会刷新页面
    19. document.getElementById('btn1').addEventListener('click', () => {
    20. const state = { name: 'page1' }
    21. console.log('切换路由到', 'page1')
    22. history.pushState(state, '', 'page1') // 重要!!
    23. })
    24. //3. 监听浏览器前进、后退
    25. window.onpopstate = (event) => { // 重要!!
    26. console.log('onpopstate', event.state, location.pathname)
    27. }
    28. // 需要 server 端配合,可参考
    29. // https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
    30. script>
    31. body>
    32. html>

    1 基本使用

    v3.5.2

    : 路由链接, 生成路由链接
    : 路由视图, 显示当前路由组件
    : 缓存路由组件对象

    main.js

    1. import Vue from 'vue';
    2. import router from './router';//index.js可以简写
    3. new Vue({
    4. el: '#app',
    5. router,
    6. components: { App },
    7. template: ''
    8. });

    router/index.js

    1. import Vue from 'vue';
    2. import VueRouter from 'vue-router';
    3. import {routes} from './routes.js';
    4. Vue.use(VueRouter);
    5. const router = new VueRouter({
    6. mode: 'history',//该模式兼容性差
    7. routes
    8. });
    9. export default router;

    router/routes.js

    1. export const routes=[
    2. {
    3. path: '/',
    4. redirect: '/home,//重定向
    5. },
    6. {
    7. path: '/home',
    8. component: Home,
    9. name:'MyHome',//命名路由
    10. },
    11. {
    12. path: '/about',
    13. component: About
    14. },
    15. ]

    hello.vue

    1. <div id="app">
    2. <h1>Hello App!h1>
    3. <p>
    4. <router-link to="/home" active-class="active">Go to Homerouter-link>
    5. <router-link :to="{name:'MyAbout',params:{id:1}}" replace>Go to Aboutrouter-link>
    6. p>
    7. <router-view>router-view>
    8. div>

    2 嵌套路由

    1. export const routes=[
    2. {
    3. path: '/',
    4. redirect: '/home',
    5. },
    6. {
    7. path: '/home',
    8. component: Home,
    9. redirect: '/home/profile',//嵌套路由重定向
    10. children: [//嵌套路由规则
    11. {
    12. path: 'profile',
    13. component: UserProfile,
    14. },
    15. {
    16. path: 'posts',
    17. component: UserPosts,
    18. },
    19. ],
    20. },
    21. {
    22. path: '/about',
    23. component: About
    24. },
    25. ]

    3 路由传参

    $route:路由参数对象:包含params/query/path/fullpath(query参数)/meta

    $router:路由器对象:包含控制路由跳转的方法(push/replace/back)

    3.0 路由的props配置 

    作用:让路由组件更方便的收到参数。

    1. {
    2. name:'xiangqing',
    3. path:'detail/:id',
    4. component:Detail,
    5. //第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
    6. // props:{a:900}
    7. //第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
    8. // props:true
    9. //第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
    10. props(route){
    11. return {
    12. id:route.query.id,
    13. title:route.query.title
    14. }
    15. }
    16. }

    3.1 params

    1. "/about/68">Go to About
    2. export const routes=[
    3. {
    4. path: '/',
    5. redirect: '/home',
    6. },
    7. {
    8. path: '/home',
    9. component: Home
    10. },
    11. {
    12. path: '/about/:mid',//使用占位符声明接收params参数
    13. component: About,
    14. props:true,//开启后,组件中可直接访问mid,需要声明接收
    15. },
    16. ]
    17. const {mid} = this.$route.params

    3.2 query 

    1. <router-link :to="/home/message/detail?id=666&title=你好">跳转router-link>
    2. <router-link
    3. :to="{
    4. path:'/home/message/detail',
    5. query:{
    6. id:666,
    7. title:'你好'
    8. }
    9. }"
    10. >跳转router-link>
    11. $route.query.id

    4 编程式导航

    this.$router.push(‘/home/’+id)//增加一条历史记录

    this.$router.replace({name:'MyAbout',params:{id:1}})//替换当前历史记录

    this.$router.go()

    this.$router.back()

    this.$router.forward()

    5 导航守卫

    导航守卫可以控制路由的访问权限。

    5.1 全局守卫

    全局前置守卫:初始化时执行、每次路由切换前执行(案例:登录后,才可以访问主页

    全局后置守卫:初始化时执行、每次路由切换后执行(修改网页title)

    1. const router = new VueRouter()
    2. // 全局前置守卫:三个参数
    3. router.beforeEach(function(to, from, next) {
    4. if (pathArr.indexOf(to.path) !== -1) {//判断当前要导航的路由是否需要权限
    5. const token = localStorage.getItem('token')
    6. if (token) {//有权限
    7. next()//有token,放行
    8. } else {
    9. next('/login')//无token,强制登录
    10. }
    11. } else {//无权限
    12. next()//放行
    13. }
    14. })
    15. //全局后置守卫
    16. router.afterEach((to,from)=>{
    17. console.log('afterEach',to,from)
    18. if(to.meta.title){
    19. document.title = to.meta.title //修改网页的title
    20. }else{
    21. document.title = 'vue_test'
    22. }
    23. })
    24. export default router

    注意:next(false)表示不允许跳转

    5.2 独享守卫

    在路由配置上定义路由独享守卫 

    1. const routes = [
    2. {
    3. path: '/users/:id',
    4. component: UserDetails,
    5. beforeEnter: (to, from) => {
    6. // reject the navigation
    7. return false
    8. },
    9. },
    10. ]

    5.3 组件内守卫

    1. //进入守卫:通过路由规则,进入该组件时被调用
    2. beforeRouteEnter (to, from, next) {
    3. },
    4. //离开守卫:通过路由规则,离开该组件时被调用
    5. beforeRouteLeave (to, from, next) {
    6. }

    6 路由懒加载

    const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')

    7 v4.x

    vue-router 3.x结合vue2使用

    vue-router 4.x结合vue3使用

    主要区别:创建路由模块的方式不同

    1. import {createRouter,createWebHashHistory} from 'vue-router'
    2. const router = createRouter({
    3. history: createWebHashHistory(),
    4. routes,
    5. linkActiveClass:'router-link-active',//激活的 RouterLink 的默认类
    6. })
    7. // 创建并挂载根实例
    8. const app = Vue.createApp({})
    9. app.use(router)

    路由跳转

    1. import { useRouter } from 'vue-router';
    2. setup(props, ctx) {
    3. const router = useRouter();
    4. const onClickLeft = () => {
    5. router.go(-1);
    6. ctx.emit('handleBack');
    7. };
    8. return {
    9. onClickLeft,
    10. };
    11. },

  • 相关阅读:
    宝立食品IPO股价八连涨 是业绩支撑还是资本迷局?
    他潜伏三年想插它后门,最终还是输给了另一个他
    财务工作者,是否需要学习 Python?
    FreeRTOS 消息队列 详解
    Maven 插件
    聚观早报|高德发布安全出行大模型;小鹏G9焕新上市
    切换挂载盘
    Beautiful Soup4语法讲解使用
    华为云云耀云服务器L实例评测|定时给微信群中推送每日新闻及生活小常识
    深入剖析:HTML页面从用户请求到完整呈现的多阶段加载与渲染全流程详解
  • 原文地址:https://blog.csdn.net/weixin_46151381/article/details/127670043