vue3 setup router的使用教程
文章目錄
- vue3 setup router的使用教程
- 1. 安裝
- 2. 使用(創建路由實例)
- 3. 路由跳轉
- 3.1 通過router-link標簽跳轉
- 3.2 通過js代碼跳轉
- 4. 接收參數
- 4.1 通過query接收參數
- 4.2 通過params接收參數
- 5. 路由守衛
- 5.1 全局守衛
- 5.2 路由獨享守衛
- 5.3 組件內守衛
- 6. 路由懶加載
- 7. 路由嵌套
- 8. 路由別名
- 9. 路由重定向
- 10. 路由滾動行為
- 11. 獲取所有路由
- 12. 獲取當前路由
setup中沒有this,所以我們需要引入vue-router的實例,然后通過實例來操作路由。
操作和之前有一些差異,所以這里記錄一下。
1. 安裝
npm install vue-router
2. 使用(創建路由實例)
import { createRouter, createWebHistory } from 'vue-router'
const routes = [{path: '/',name: 'Home',component: Home}]
const router = createRouter({/*** 這里可以配置路由模式* * @description 1. hash模式@example import { createRouter, createWebHashHistory } from 'vue-router'history: createWebHashHistory(),* @description 2. history模式* 如下:*/history: createWebHistory(),routes,
})
export default router
3. 路由跳轉
請先引入router實例,接下來的操作都是基于我們創建的router實例。
import router from './router'
3.1 通過router-link標簽跳轉
<router-link to="/">Home</router-link>
3.2 通過js代碼跳轉
import router from './router'// 通過query傳參
router.push({path: '/about',query: {id: 1}
})
// 通過params傳參
router.push({path: '/about',params: {id: 1}
})// 或者
router.push('/about?id=1')
4. 接收參數
4.1 通過query接收參數
import router from './router'
onMounted(() => {console.log(router.currentRoute.value.query.id)
})
4.2 通過params接收參數
import router from './router'
onMounted(() => {console.log(router.currentRoute.value.params.id)
})
5. 路由守衛
5.1 全局守衛
import router from './router'
router.beforeEach((to, from, next) => {// to: 即將要進入的目標 路由對象// from: 當前導航正要離開的路由// next: 調用該方法后,才能進入下一個鉤子next()
})
5.2 路由獨享守衛
const routes = [{path: '/',name: 'Home',component: Home,beforeEnter: (to, from, next) => {next()}}]
5.3 組件內守衛
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
onBeforeRouteLeave((to, from, next) => {console.log(to, from)next()
})
onBeforeRouteUpdate((to, from, next) => {console.log(to, from)next()
})
6. 路由懶加載
const routes = [{path: '/',name: 'Home',component: () => import('../views/Home.vue')}]
7. 路由嵌套
const routes = [{path: '/',name: 'Home',component: Home,children: [{path: 'about',name: 'About',component: () => import('../views/About.vue')}]}]
8. 路由別名
const routes = [{path: '/',name: 'Home',component: Home,alias: '/home'}]
9. 路由重定向
const routes = [{path: '/',name: 'Home',component: Home,redirect: '/home'}]
10. 路由滾動行為
const router = createRouter({history: createWebHistory(),routes,scrollBehavior(to, from, savedPosition) {// to: 即將要進入的目標 路由對象// from: 當前導航正要離開的路由// savedPosition: 滾動條的坐標return {x: 0,y: 0}}
})
11. 獲取所有路由
import router from '@/router';
console.log(router.options.routes)
12. 獲取當前路由
import router from '@/router';
console.log(router.currentRoute.value)