Vue路由配置方法詳細介紹
手動配置Vue-router環(huán)境
1、下載包: npm i vue-router --save或者 npm i vue-router --S 或者用cdn引入
2、創(chuàng)建路由的js文件(路由、子路由、重定向、開啟history模式)
createRouter、createWebHistory
//路由文件
import { createRouter, createWebHistory } from 'vue-router' //將createRouter、createWebHistory引入vue
const routes = [
{
path: '/', //配置默認路由
name: 'home', //路由名
component: () => import("../views/home.vue"), //引入該路由使用的組件
},
{
path: '/a',
name: 'a',
component: () => import('../views/a.vue'),
redirect: '/a/son1',
children:[ //配置子路由
{
path: '/a/son1', //子路由路徑前邊必須寫父路由路徑
name: 'ason1',
component: ()=>import("../views/a-son1.vue")
}
]
},
{
path: '/b',
name: 'b',
component: () => import('../views/b.vue'),
redirect: '/b/son1', //重定向,進入/b路由時默認進入/b/son1
children:[ //配置子路由
{
path: '/b/son1', //子路由路徑前邊必須寫父路由路徑
name: 'bson1',
component: ()=>import("../views/b-son1.vue")
}
]
}
]
const router = createRouter({ //設置為history模式
history: createWebHistory(),
routes
})
export default router3、將配置的路由js文件引入到main.js中
import { createApp } from 'vue'
import App from './App.vue'
const app=createApp(App)
import router from "./router/index.js" //引入配置路由文件
app.use(router)//記得在mount之前調用
app.mount('#app')4、界面中使用router-view標簽顯示路由
組件內部跳轉路由與傳參useRouter,useRoute
vue3中,在組件內部跳轉路由 需要使用useRouter,useRoute方法
useRoute相當于以前的this.$route 跳轉路由
用法:
<template>
<h1>aaa</h1>
<router-view></router-view>
<button @click="fn">從a路由跳轉到b路由</button>
</template>
<script setup>
import {useRouter} from "vue-router"
let router=useRouter() //接收useRouter方法,在vue2中是直接使用router即可
let fn=()=>{
router.push({path:"/b",query:{name:"小獅子"}}) //path寫跳轉的路由,同樣可以傳參
}
</script>
<style scoped>
h1{
width: 400px;
height:200px;
background-color:deeppink;
}
</style>useRouter相當于this.$router 接受傳參(query、params)
注意:
1、請注意params只與name(路由文件里配置的路由name)搭配生效(不能使用path)
2、只能在setup函數(shù)內使用
用法
<template>
<h2>這是b-son1</h2>
<button @click="fn">lookquery</button>
</template>
<script setup>
import {useRoute} from "vue-router" //引入
let route=useRoute()
console.log(route.query)//如果是params傳參就用route.params接收
let fn=()=>{ //這不是setup函數(shù)內部,是取不到傳參的,返回undefined
let route=useRoute()
console.log(route)
}
</script>
<style scoped>
h2{
width: 200px;
height:100px;
background-color:aliceblue;
}
</style>結合前者代碼進行驗證,發(fā)現(xiàn)下圖狀況

當我們進行頁面跳轉時成功獲取了傳參,但不在setup函數(shù)內使用useRouter是獲取不了的
到此這篇關于Vue路由配置方法詳細介紹的文章就介紹到這了,更多相關Vue路由配置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
利用Vue3的Teleport實現(xiàn)模態(tài)對話框功能
在前端開發(fā)中,模態(tài)對話框是一種常見的用戶交互方式,它能夠有效地提示用戶、收集信息或確認操作,隨著現(xiàn)代框架的演進,Vue 3 的出現(xiàn)為我們提供了更便捷、高效的方式來處理復雜的界面布局,今天,我們將深入探討如何利用 Vue 3 的新特性 Teleport 來實現(xiàn)模態(tài)對話框2025-02-02
詳解如何在Vue中快速實現(xiàn)數(shù)據(jù)可視化大屏展示
在現(xiàn)代數(shù)據(jù)驅動的應用程序中,數(shù)據(jù)可視化大屏已經(jīng)成為了非常重要的一環(huán),通過對海量數(shù)據(jù)進行可視化展示,可以幫助用戶更好地理解和分析數(shù)據(jù),從而做出更加明智的決策,在Vue中進行數(shù)據(jù)可視化大屏展示也變得越來越流行,本文將介紹如何在Vue中快速實現(xiàn)數(shù)據(jù)可視化大屏展示2023-10-10

