The use of routing in Vue3

1. Create a route

Vue3Routing in is similar to routing Vue2.xin , Vue3there are a few points to note when creating routes in :

  • There are two routing modes, one is createWebHashHistorythe hash mode, and the other is that these two correspond to the sum createWebHistoryin Vue2.x ;hashhistory
  • Vue2.x creates routes new VueRouter()by , and Vue3 by createRouter;
// vue3.x
import {
    
     createRouter } from 'vue-router'
const router = createRouter({
    
    
    history: createWebHistory(),
    routes
})
// vue2.x
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
    
    
    mode: 'history',
    routes
})

After defining the route, you need to register the route main.jsin

import {
    
     createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
createApp(App).use(router).mount('#app')

If you want to access the routing object in a page or component, you useRoutercan useRouteget it through and ;

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
console.log(useRouter) // 相当于 Vue2.x 中的 this.$router
console.log(useRoute) // 相当于 Vue2.x 中的 this.$route
</script>

2. Routing parameters

  • dynamic pass value
// 路由文件
const routes = [
    {
    
    
        path: '/home/:id',
        // 路由懒加载
        component: () => import('@/views/home.vue'),
        meta: {
    
    
            name: '首页'
        }
    }
]
  • programmatic navigation
<script setup lang="ts">
import { useRouter } from 'vue-router'
const router = useRouter()
// 方式一: 直接写路由地址
router.push('/home')
// 方式二:带有路径的对象
router.push({ path: '/home' })
// 方式三:命名路由带参数, params 需要和 name 搭配,不能和 path 搭配,否则会无效
router.push({ name: 'home', params: { id: 1 } })
// 方式四:带查询参数
router.push({ path: '/home', params: { id: 1 } })
router.push({ path: '/home', query: { id: 1 } })
// 方式五:带 hash, 表示为 /home#hash
router.push({ path: '/home', hash: 'hash' })
</script>
  • Declarative Navigation
<!-- 方式一 -->
<router-link to="/home">Home</router-link>
<!-- 方式二:path 路径 -->
<router-link :to="{ path: '/home' }">Home</router-link>
<!-- 方式三:需要在路由对象中定义 name 值 -->
<router-link :to="{ name: 'home' }">Home</router-link>

3. Routing switch scrolls to the top

Vue3There are two ways to scroll the page scroll bar to the top when we switch routes, which are route guard hook afterEachand setting scrollBehaviormethod ;

Routing guard hook afterEach

router.afterEach((to, from, next) => {
    
    
    window.scrollTo(0, 0)
})

Set scrollBehavior method

const router = createRouter({
    
    
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savePosition) {
    
    
        return {
    
    
            top: 0
        }
    }
})

Guess you like

Origin blog.csdn.net/Ljwen_/article/details/125258368