vue-router 相关

路由模式(hash、h5-history)

hash不需要后端支持,history需要后端支持

  • hash:http://xxx.com/#/xxx
  • history:http://xxx.com/xxx

路由配置(动态路由、懒加载)

const router = new VueRouter({
  mode: 'history',
  routes: [
   { path: '/', redirect: '/home' },
    {
      path: '/home',
      component: XXX,
      children: [...]
    }
  ]
})

$route 和 $router

$router

对路由的一些操作

$router.push({path:'home'})本质是向history栈中添加一个路由
$router.replace({path:'home'})//替换路由,没有历史记录

$route

是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等

  • route.path
    字符串,等于当前路由对象的路径,会被解析为绝对路径,如 “/home/news” 。
  • route.params
    对象,包含路由中的动态片段和全匹配片段的键值对
  • route.query
    对象,包含路由中查询参数的键值对。例如,对于 /home/news/detail/01?favorite=yes ,会得到$route.query.favorite == ‘yes’ 。
  • route.router
    路由规则所属的路由器(以及其所属的组件)。
  • route.matched
    数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象。
  • route.name
    当前路径的名字,如果没有使用具名路径,则名字为空。

前端路由原理

稍微复杂一点的SPA,都需要路由,两种模式:hash、history
看看 url 组成:http://127.0.0.1:8001/index.html?name=yq#/aaa/bbb

  • location.protocol(http)
  • location.hostname(127.0.0.1)
  • location.host(127.0.0.1:8001)
  • location.port(8001)
  • location.pathname(/index.html)
  • location.search(?name=yq)
  • location.hash(#/aaa/bbb)
hash
  • hash 变化会触发网页跳转,即浏览器的前进、后退
  • hash 变化不会刷新页面,SPA 必需特点
  • hash 永远不会提交到 server 端
// hash 的变化包括:js 修改 url、手动修改 url、浏览器前进后退
window.onhashchange = (event) => {
  console.log(event.oldURL, event.newURL, location.hash)
}
history
  • 用 url 规范的路由,但跳转时不刷新页面
  • history.pushState 浏览器不会刷新页面
  • window.onpopstate 监听浏览器前进、后退
window.onpopstate = (event) => {
  console.log(event.state, location.pathname)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值