vue--路由

166 阅读1分钟

一. 当用户在浏览器地址栏写下url时,我们要展示哪些组件?

1.我们可以通过hash值来获取

1.hash是url的一部分

2.hash的变化 不会引起页面刷新

3.hash可以通过window.onhashchange监听到

2.实现原理:

(1)监听onhashchange的变化

(2)写配置规则,hash是xxx的时候去加载什么组件

代码图: code.png

image.png

image.png

二.导航 -router-link

  1. 格式: - <router-link  to="/">xxx</router-link>
    • 本质就是a
    • 如果匹配当前的path,它会自己添加两个class
      • router-link-exact-active
      • router-link-active 2.- 编程式- this.$router.push(  )

三- 页面跳转传参

image.png

  1. query

     传  :to="/page1?a=1&b=2" - this.$router.push( '/page1?a=1&b=2' )
        
      接 : this.$route.query.a
      
    

image.png 2. params

      传  :  to="/page1/1/2" -  this.$router.push( '/page1/1/2' )
    - 搭配:  路由配置
    -  path: '/page1/:id/:name'
    -   接
    -    this.$route.params
    

image.png

- 重定向
  • { path: '/a',  redirect: '/b' }
  • 访问/a,自动跳到/b
- 404
  • 配置到最后面
  • {path: '*', component: page404}

四. 嵌套路由

1. 场景

复杂的应用`` 例如下图为路由配置:

2.为了更好的了解去做一下如下的案例体育新闻:

一级路由入口图:

image.png

二级路由入口图:

image.png

浏览器页面

image.png