// hash 模式
// import { createRouter, createWebHashHistory } from 'vue-router'
// history 模式
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
// redirect 重定向 默認(rèn)進(jìn)入去到 home
{ path: '/', redirect: '/home' },
{
// name屬性:路由記錄獨一無二的名稱
name: 'homeCom',
// meta屬性:自定義的數(shù)據(jù)
meta: { name: 'HachimanC', age: 20 },
// 跳轉(zhuǎn)的路徑
path: '/home',
// 路由懶加載 路由分包處理 npm run build /* webpackChunkName: "homeCom" */ => 魔法注釋 分包后進(jìn)行打包后 包的名字
component: () => import(/* webpackChunkName: "homeCom" */ '../views/homeCom.vue')
},
// 傳遞 id
{ path: '/user/:id', component: () => import(/* webpackChunkName: "userCom" */ '../views/userCom.vue') },
// 路徑不正確顯示
{ path: '/:pathMatch(.*)', component: () => import(/* webpackChunkName: "notFound" */ '../views/NotFound.vue') },
]
const router = createRouter({
// history: createWebHashHistory(), // hash 模式
history: createWebHistory(process.env.BASE_URL), // history 模式
routes,
})
export default router
?html部分
<template>
<div>路由切換渲染</div>
<router-link to="/home" active-class="linkClass">首頁</router-link>
<!-- replace 替換 點擊不會返回上一頁直接跳轉(zhuǎn)瀏覽器首頁 -->
<router-link to="/user/123" replace>用戶123</router-link>
<router-link to="/user/321">用戶321</router-link>
<button class="btn" @click="jumpHandler('/home')">首頁</button>
<button class="btn" @click="jumpHandler('/user/123')">用戶</button>
<router-view></router-view>
</template>
js部分
<script setup>
import { useRouter } from 'vue-router'
const route = useRouter()
const jumpHandler = path => {
// route.replace(path)
route.push(path+`?name=Hachiman&age=20&id=123`)
}
</script>
<style scoped>
.linkClass {
color: #ff0000;
font-size: 20px;
}
.btn {
border: none;
background: #ff0000;
margin: 0 10px;
}
</style>
?html頁面使用路由傳來的參數(shù)
<template>
<h2>
home組件 傳遞來的參數(shù){{ $route.query }}
</h2>
</template>
?獲取router跳轉(zhuǎn)id文章來源:http://www.zghlxwxcb.cn/news/detail-678296.html
<template>
<h2>用戶id: {{ $route.params.id }}</h2>
<button @click="backHandler">返回</button>
</template>
<script setup>
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
const route = useRoute()
console.log(route.params.id)
// 獲取 route 跳轉(zhuǎn) id
onBeforeRouteUpdate((to, from) => {
console.log('from:', from.params.id)
console.log('to:', to.params.id)
})
const router = useRouter()
const backHandler = () => {
// 后退 和 前進(jìn)
// router.back()
// router.forward()
// go(1) => forward()
// go(-1) => back()
router.go(-1)
}
</script>
獲取?路由跳轉(zhuǎn)錯誤地址文章來源地址http://www.zghlxwxcb.cn/news/detail-678296.html
<template>
<div class="notFound">路徑{{ $route.params.pathMatch }}不正確</div>
</template>
<style>
.notFound{
font-size: 30px;
color: red;
}
</style>
到了這里,關(guān)于Vue3 Vue-Router詳解 Vue3配置hash 和 history路由、Vue3封裝的路由hook函數(shù)(useRouter,useRoute)的使用 路由懶加載、路由分包處理、魔法注釋的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!