Vue中路由的使用方法實例詳解
1 作用
能夠按不同的訪問路徑,展示不同組件的內容。
2 使用方法
2.1 安裝路由
在項目的終端或者路徑下的命令提示符窗口中,寫入以下命令(其中的4是指版本為4):
npm install vue-router@4
2.2 創(chuàng)建路由并導出
①在src目錄下創(chuàng)建一個router文件夾,再在其中創(chuàng)建index.js文件
注:當然,其它名字.js也可以,只不過2.3的導入需要額外書寫內容
②向index.js中書寫以下格式內容:
//引入依賴
import { createRouter, createWebHistory } from 'vue-router'
//導入組件
//xx和yy可以替換為實際的內容
import XxVue from '@/views/Xx.vue'
import YyVue from '@/views/Yy.vue'
//定義路由關系
const routes = [
//這樣就可以通過http://localhost:5173/Xx訪問Xx.vue的內容了
{ path: '/Xx', component: XxVue},
//同理,可以訪問Yy.vue。并將其作為默認頁面
{ path: '/', component: YyVue}
]
//定義路由
const router = createRouter({
//history是路由模式,還有一種哈希方式(createWebHashHistory),配置方式自行探索
history: createWebHistory(),
routes: routes
})
//導出路由
export default router2.3 在應用實例中使用vue-router
在main.js中引入如下內容:
//這里只展示主要內容,其它內容...
import { createApp } from 'vue'
import App from './App.vue'
//導入路由,默認導入index.js
//如果不是index.js,而是xx.js,則from '@/router/xx.js'
import router from '@/router'
const app = createApp(App)
app.use(router)
app.mount('#app')2.4 聲明router-view,展示組件內容
在App.vue中的<template>內添加如下,進去的默認頁面就是Yy.vue了:
<template>
<router-view></router-view>
</template>2.5 頁面跳轉
如果想在某個函數(shù)執(zhí)行之后,想跳轉某個頁面,可以如下使用:
①在該函數(shù)所在的頁面導入,如xx.vue:
import {useRouter} from 'vue-router'②找到該函數(shù),并向其中添加如下內容:
const xx = async() => {
//其它內容...
//router.push跳轉到指定頁面,這里是默認頁面
router.push('/')
}3 補充內容-子路由
如下圖所示,App.vue使用的叫一級路由,X.vue使用的就屬于二級路由(X->Z,X->H),其中二級路由就可以稱為一級路由的子路由,:

如element-ui中的例子所示,要在當前頁面訪問的Option1就屬于子路由:

配置如下,在index.js中新增一些內容:
//引入依賴
import { createRouter, createWebHistory } from 'vue-router'
//導入組件
//xx和yy可以替換為實際的內容
import XxVue from '@/views/Xx.vue'
import YyVue from '@/views/Yy.vue'
import ZzVue from '@/views/Zz.vue'
import HhVue from '@/views/Hh.vue'
//定義路由關系
const routes = [
//這樣就可以通過http://localhost:5173/Xx訪問Xx.vue的內容了
{ path: '/Xx', component: XxVue},
//同理,可以訪問Yy.vue。并將其作為默認頁面
//redirect:'/func/xyz'是將Zz.vue頁面作為進入'/'默認的訪問的頁面
//children:子路由
{ path: '/', component: YyVue,redirect:'/func/xyz', children:[
{ path: '/func/xyz', component: ZzVue},
{ path: '/func/zxy', component: HhVue},
]}
]
//定義路由
const router = createRouter({
//history是路由模式,還有一種哈希方式(createWebHashHistory),配置方式自行探索
history: createWebHistory(),
routes: routes
})
//導出路由
export default router到此這篇關于Vue中路由的使用方法的文章就介紹到這了,更多相關Vue路由使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vite.config.ts配置之自動導入element-puls方式
這篇文章主要介紹了vite.config.ts配置之自動導入element-puls方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
vue?element-ui如何在el-tabs組件最右側添加按鈕
這篇文章主要介紹了vue?element-ui如何在el-tabs組件最右側添加按鈕問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

