Vue Router @ Littlechai | 2021-10-06T23:02:56+08:00 | 2 分钟阅读 | 更新于 2021-10-06T23:02:56+08:00

基本使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Home from '../components/Home.vue'
import Movie from '../components/Movie.vue'
import Tab1 from '../components/Tab1.vue'
import Tab2 from '../components/Tab2.vue'

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
   //重定向
  { path: '/', redirect: '/home' },
  {
    path: '/home',
    component: Home,
    //路由嵌套
    children: [
      { path: 'tab1', component: Tab1 },
      { path: 'tab2', component: Tab2 }
    ]
  },
  { path: '/movie', component: Movie }
]

const router = new VueRouter({
  routes
})

export default router

重定向可以解决空页面 默认路由的问题

**默认路由:**若path为空,则为默认路由

动态路由

再path中用:来表示动态参数

props传参

props: true 开启后可在vue中用props获得动态参数

也可由 this.$route.params.动态参数来获得

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Home from '../components/Home.vue'
import Movie from '../components/Movie.vue'
import Tab1 from '../components/Tab1.vue'
import Tab2 from '../components/Tab2.vue'

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [

  { path: '/movie/:id', component: Movie, props: true}
]

const router = new VueRouter({
  routes
})

export default router

tips

this.$route 中 path 是路径部分, fullpath 为完整路径,包含 query 查询参数

编程式导航

this.$router.push('hash地址') 增加一条历史记录

this.$router.replace('hash地址') 替换当前历史记录

this.$router.go(数值 n)

go的简化this.$router.back() this.$router.forward()

Tips: 行内使用时 this 必须省略

导航守卫

router.beforEach((to, from, next) => {}) 只要发生跳转,就会触发回调函数

1
2
3
4
5
6
router.beforEach((to, from, next) => {
	//to 将要访问的路由信息对象
    //from 将要离开的路由信息对象
    //next 是一个函数,调用next()表示放行,允许这次路由导航,也可以强制跳转next('/hash地址')
    //不允放行next(false)
})

路由传参

使用query

注意传参不能传对象,要转成JSON

1
2
3
4
5
6
to="{
     path: '/wizz-index',
     query: {
     indexData: [...this.userData],
     },
}"

this.$router.push

1
2
3
4
5
6
this.$router.push({
   path: "/wizz-index",
   query: {
     indexData: JSON.stringify(this.userData["主页"]),
   },
});

© 2021 - 2022 小柴Yeah

Powered by Hugo with theme Dream.

avatar

小柴YeahThe time is no time, when it is past