vueRouter

89 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1、路由的hash和history的区别?

1. hash模式

  • hash模式写法有#
  • 不会向服务器发送请求,对后端没有影响。改变hash值,不会重新加载页面。
  • hash模式的原理是 onhashchange() 事件
window.onhashchange = function(event) {
    console.log(event.oldURL, event.newURL);
    let hash = location.hash.slice(1);
}
  • 使用onhashchange的好处,页面在hash值变化时,不用向后端发起请求,window就可以监听事件的变化,并按规则加载相应代码。

  • hash值变化对应的url会被浏览器记录下来,可以使用前进后退

2. history模式

  • history写法没有 #,相比hash写法更好看
  • history需要后台配置的支持,如果后台没有正确配置,访问时会返回404
  • history模式分为修改历史状态,切换历史状态
    • 修改历史状态:是 pushState()replaceState() 方法,这两个方法用于浏览器的历史记录栈,提供历史记录修改的功能。只是当他们进行修改时,虽然修改了url,但浏览器不会立即向后端发送请求。如果要做到改变url但又不刷新页面的效果,就需要前端用上这两个API。
    • 切换历史状态: 包括forward()back()go()三个方法,对应浏览器的前进,后退,跳转操作。
  • history模式的话需要在路由中加上mode:'history'
  • 在刷新页面的时候,如果没有相应的路由或资源,就会刷出404来。

2、如何获取页面的hash变化?

  • 监听$route的变化
// 监听,当路由发生变化的时候执行
watch: {
    $route: {
        handler: function(val, oldVal){
            console.log(val);
        },
        // 深度观察监听
        deep: true
    }
},
  • window.location.hash读取#值: window.location.hash 的值可读可写,读取来判断状态是否改变,写入时可以在不重载网页的前提下,添加一条历史访问记录。

3、$route$router 的区别?

  • $router是路由实例,包含了路由的跳转,钩子函数等。
this.$router.push({
    path: '/app/troubleshooting/edit',
    query: {
        productAlias: this.productAlias,
    }
})
  • $route 是路由信息,包括path,params,hash,query等参数
const policyAlias = this.$route.query.policyAlias

4、如何定义动态路由?

path: '/detail/:id'

path: 'detail/123'

5、导航守卫

  1. 全局
  • router.beforeEach
  • router.beforeResolve
  • router.afterEach
  1. 路由独享守卫
  • router.beforeEnter
  1. 组件内
  • beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave

6、Vue-router跳转和location.href有什么区别

  • 使用 location.href= /url 来跳转,简单方便,但是刷新了页面;
  • 使用 history.pushState( /url ) ,无刷新页面,静态跳转;
  • 引进 router ,然后使用 router.push( /url ) 来跳转,使用了 diff 算法,实现了按需加载,减少了 dom 的消耗。其实使用 router 跳转和使用 history.pushState() 没什么差别的,因为vue-router就是用了 history.pushState() ,尤其是在history模式下。

7、params和query的区别

1. params

  • params不在url中显示
  • params与path使用的话不生效
  • params要与name一起使用,这个name是vue-router中的name
  • 获取params内容this.$route.params
this.$router.push({
  name: 'FilesourceEdit',
  params: { sourceId: row.sourceId },
})
console.log(this.$route.params) // {sourceId: 1}

{
  path: 'filesource/filesourceEdit',
  name: 'FilesourceEdit',
  component: () => import('@/viewsAdmin/filesource/filesourceEdit'),
},
// 不生效
this.$router.push({
  params: { sourceId: row.sourceId },
  path: '/admin/filesource/filesourceEdit',
})

2. query

  • query在url中显示
  • query与path,name使用都可以
  • 获取query内容this.$route.query
this.$router.push({
  path: '/admin/filesource/filesourceEdit',
  name: 'FilesourceEdit',
  query: { sourceId: row.sourceId },
})
console.log(this.$route.query) // {sourceId: 1}

{
  path: 'filesource/filesourceEdit',
  name: 'FilesourceEdit',
  component: () => import('@/viewsAdmin/filesource/filesourceEdit'),
},

image.png