vueRouter常用属性

vueRouter常用属性

base

基本的路由请求的路径

如果整个单页应用服务在 /app/ 下,然后 base 就应该设为 "/app/",所有的请求都会在url之后加上/app/

javascript 复制代码
new VueRouter({
    base: '/app/',
    ...
  });

mode

设置路由工作模式hash或history

hash

http:/8000/#/hello

  • Vue-router 默认使用 hash 模式,使用 hash 模式时 url 中始终有 # 号。
  • 不会刷新页面,也不会发起新的 HTTP 请求,只是实现客户端页面的定位
  • #后面的字符不会被发送到服务器端,# 可以修改浏览器的访问历史记录。
  • hash 模式是通过改变锚点(#)来更新页面 url,并不会触发页面重新加载。
  • 通过window.onhashchange() 监听到hash 的改变,从而处理路由。

history

http:/8000/hello

  • 使用 history 模式时URL中不带 # 号。
  • 利用 history.pushState 和 history.replaceState API 来完成 URL 跳转而无须重新加载页面。
  • 刷新会请求服务器,如果服务器中没有相应的响应或者资源,则会刷新出来404页面

history模式下可能会遇到的问题及解决方案

  • 使用history模式通常本地调试没有什么问题,但是一旦发布到测试或生产环境,则会出现页面白屏或者刷新页面白屏的现象,这种问题的出现是因为前端和服务端没有做相应的配置
javascript 复制代码
//前端设置
module.exports = {
  // publicPath默认值是'/',即你的应用是被部署在一个域名的根路径上
  // 设置为'./',可以避免打包后的静态页面空白
  // 当在非本地环境时,这里以项目test为例,即打包后的h5项目部署服务器的test目录下
  // 那么这里就要把publicPath设置为/test/,表示所有的静态资源都在/test/里
  // 打包部署后,会发现index.html引用的静态资源都添加了路径/test/
  publicPath: process.env.NODE_ENV == 'development' ? './' : '/test/',
  ......
}

///服务端设置
location /test{
  ...
  try_files $uri $uri/ /test/index.html 
  //location /test表示项目部署在了 /test目录下,这里要跟vue.config.js里的publicpath的值保持一致。

之所以刷新页面白屏,其实是因为路由资源不存在
}

routes

属性设置匹配的路由地址path与路由组件component

javascript 复制代码
new Router({
    ...
    routes: [
        {
            path: '/',
            component: () => import('.iews/Index'),
            name: "home",
            children: [
                { path: '/home', name: "home", meta: { title: '管理' }, component: () => import('.src/home/Index') },
            ]
        },
        {
        path: string,//路由路径
        component: Component, // 当前路由匹配时显示的路由组件
        name: string, // 命名路由
        redirect: string | Location | Function, // 路由重定向
        props: boolean | Object | Function,  //路由传参
        alias: string | Array<string>, // 路由别名
        children: Array<RouteConfig>, // 嵌套路由
        beforeEnter: (to: Route, from: Route, next: Function) => void, //路由守卫
        caseSensitive: boolean, // 匹配规则是否大小写敏感?(默认值:false)
      }

        }
    ]
})

props配置(最佳方案)

javascript 复制代码
{ // 二级路由
    path: 'message',
    component: Message,
    children: [
        { // 三级路由
            name: 'detail',
            path: 'details/:id/:title/:desc', // 配置占位符
            component: Details,
            props(route){ // router每次调的时候会把 $route 传进来,你想怎么取就怎么取!
                return {
                    id: route.params.id,
                    title: route.params.title,
                    desc: route.params.desc
                }
            }
            // es6解构赋值写法更简单
            //props({query: {id, title, desc}}){
            //    return {id, title, desc}
            //}
        }
    ]
}

scrollBehavior

置路由跳转时,页面滚动条的位置

很多情况下,用户希望查看详情页以后,返回列表页刚刚浏览的位置,但由于列表页组件已经被销毁,所以我们重新返回到列表页后页面会置顶,就需要重新下拉查看列表,这样就做了很多没有必要的操作。

javascript 复制代码
new VueRouter({
    ...
    scrollBehavior() {
      return { x: 0, y: 0 };
    },
  });

也可以使用如下两种方案(更推荐使用scrollBehavior方案)

  • 使用路由守卫),在beforRouterLeave的路由钩子记录当前页面滚动位置
javascript 复制代码
//在页面离开时记录滚动位置
beforeRouteLeave (to, from, next) {
    this.scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    next()
  },
 
//进入该页面时,用之前保存的滚动位置赋值
beforeRouteEnter (to, from, next) {
    next(vm => {
      document.body.scrollTop = vm.scrollTop
    })
  },
  • 使用keep-alive缓存
javascript 复制代码
//App.vue
<template>
  <div id="app">
    <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" />
  </div>
</template>

//router.js
 routes: [
    {
      path: '/',
      name: 'List',
      component: () => import('./list.vue'),
      meta: {
        keepAlive: true // 需要缓存
      }
    },
    {
      path: '/content/:contentId',
      name: 'content',
      component: () => import('./content.vue'),
      meta: {
        keepAlive: false // 不需要缓存
      }
    },
]
相关推荐
超哥--4 小时前
B站视频内容智能分析系统(九):React 前端与管理面板
前端·react.js·前端框架
Cutecat_6 小时前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
qq_422152577 小时前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
kyriewen7 小时前
手写 Promise.all、race、any:不到 30 行代码,解决并发异步的所有姿势
前端·javascript·面试
brucelee1868 小时前
OpenClaw 浏览器控制(Chrome MCP)完整教程
前端·chrome
ct9788 小时前
React 状态管理方案深度对比
开发语言·前端·react
胡志辉的博客8 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·chrome·chromium·event loop
代码不加糖9 小时前
js中不会冒泡的事件有哪些?
前端·javascript·vue.js
懂懂tty9 小时前
Vue2与Vue3之间API差异
前端·javascript·vue.js
AI焦点9 小时前
跨越协议鸿沟:Tool Use状态机从Anthropic到OpenAI兼容体系的适配要点
前端·人工智能