方式一:通過動(dòng)態(tài)組件的方式躯喇,監(jiān)聽瀏覽器 hashchange
事件或使用 History API 來更新當(dāng)前組件
參考:https://cn.vuejs.org/guide/scaling-up/routing.html#official-router
<script setup>
import { ref, computed } from 'vue'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'
const routes = {
'/': Home,
'/about': About
}
const currentPath = ref(window.location.hash)
window.addEventListener('hashchange', () => {
currentPath.value = window.location.hash
})
const currentView = computed(() => {
return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>
<template>
<a href="#/">Home</a> |
<a href="#/about">About</a> |
<a href="#/non-existent-path">Broken Link</a>
<component :is="currentView" />
</template>
優(yōu)點(diǎn):純 Vue3 就可以實(shí)現(xiàn)炼蹦,不需要引入額外的路由庫
缺點(diǎn):需要手?jǐn)]事件監(jiān)聽代碼,編譯后體積較小
方式二:使用路由庫 vue-router 進(jìn)行路由
<script lang='ts' setup>
import { RouteLocationRaw, useRouter } from 'vue-router';
// 選擇菜單時(shí)奶陈,在 <router-view> 渲染對(duì)應(yīng)的組件
const router = useRouter()
function handleSelete(index: RouteLocationRaw) {
router.push(index)
}
</script>
<template>
<div class="common-layout">
<el-container>
<!-- Element Plus Menu: https://element-plus.gitee.io/zh-CN/component/menu.html -->
<el-menu class="el-menu-demo" mode="horizontal" :default-active="$route.path" :ellipsis="false"
@select="handleSelete">
<el-menu-item index="/aichat">ChatGPT</el-menu-item>
<el-menu-item index="/aitranslate">AI翻譯</el-menu-item>
<el-menu-item index="/aitext">AI文本</el-menu-item>
</el-menu>
<div style="height: 50px"></div>
<router-view></router-view>
</el-container>
</div>
</template>
優(yōu)點(diǎn):路由功能強(qiáng)大怯屉,靈活性強(qiáng)
缺點(diǎn):需要引入路由庫 vue-router蔚舀,編譯后體積較大
方式三:使用 element plus 菜單的 router 進(jìn)行路由
<script lang='ts' setup>
</script>
<template>
<div class="common-layout">
<el-container>
<!-- Element Plus Menu: https://element-plus.gitee.io/zh-CN/component/menu.html -->
<el-menu class="el-menu-demo" mode="horizontal" :default-active="$route.path" :ellipsis="false" router>
<el-menu-item index="/aichat">ChatGPT</el-menu-item>
<el-menu-item index="/aitranslate">AI翻譯</el-menu-item>
<el-menu-item index="/aitext">AI文本</el-menu-item>
</el-menu>
<div style="height: 50px"></div>
<router-view></router-view>
</el-container>
</div>
</template>
router 屬性啟用后,可以省掉 handleSelete() 方法锨络,就變成純 element plus 路由了
優(yōu)點(diǎn):實(shí)現(xiàn)簡(jiǎn)單赌躺,純 element plus 的 menu 組件就可以實(shí)現(xiàn)(當(dāng)然底層渲染時(shí)還是會(huì)轉(zhuǎn)換成 ts 代碼的),不需要手?jǐn)]任何邏輯
缺點(diǎn):需要引入 UI 庫 element plus羡儿,編譯后體積較大