【Vue3+ElementPlus】菜单路由功能比较
2023-02-25 本文已影响0人
MasonChan
方式一:通过动态组件的方式,监听浏览器 hashchange
事件或使用 History API 来更新当前组件
参考: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>
优点:纯 Vue3 就可以实现,不需要引入额外的路由库
缺点:需要手撸事件监听代码,编译后体积较小
方式二:使用路由库 vue-router 进行路由
<script lang='ts' setup>
import { RouteLocationRaw, useRouter } from 'vue-router';
// 选择菜单时,在 <router-view> 渲染对应的组件
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>
优点:路由功能强大,灵活性强
缺点:需要引入路由库 vue-router,编译后体积较大
方式三:使用 element plus 菜单的 router 进行路由
<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 路由了
优点:实现简单,纯 element plus 的 menu 组件就可以实现(当然底层渲染时还是会转换成 ts 代码的),不需要手撸任何逻辑
缺点:需要引入 UI 库 element plus,编译后体积较大