共计 2044 个字符,预计需要花费 6 分钟才能阅读完成。
Vue 3 + Pinia + ElementPlus 实现响应式 Header 组件
在前端开发中,组件的交互和状态管理是非常关键的。本文将详细介绍如何使用 Vue 3 和 Pinia 实现一个响应式的 Header 组件,包括菜单的折叠与展开、标签页的显示与关闭等逻辑。
1. 组件布局
Header 组件使用 Flex 布局,主要分为两个部分:左侧菜单折叠按钮和标签页,右侧用户信息下拉菜单。
template>
div class="header-container">
div class="header-left">
el-icon class="icon-menu" size="25" @click="handleMenu">
Fold />
el-icon>
ul class="tags">
li v-for="tag in menuStore.tagList" :key="tag.path" class="tag"
:class="{'is-active': tag.path === route.path}" @click="handleClick(tag)"
>
el-icon>
component :is="tag.icon">component>
el-icon>
span>{{tag.name}}span>
span class="close-icon" @click.stop="closeTab(tag, index)">×span>
li>
ul>
div>
div class="header-right">
el-dropdown trigger="click">
div class="el-dropdown-link">
el-avatar class="avatar" :size="40" src="path-to-user-avatar.jpg">el-avatar>
p class="user-name">adminp>
div>
template #dropdown>
el-dropdown-menu>
el-dropdown-item> 登出 el-dropdown-item>
el-dropdown-menu>
template>
el-dropdown>
div>
div>
template>
2. Pinia 状态管理
使用 Pinia 管理菜单的折叠状态以及标签页列表。Pinia 提供了简洁而强大的状态管理功能,特别适合 Vue 3。
import { useMenuStore } from '@/stores';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const menuStore = useMenuStore();
const handleMenu = () => {
menuStore.setMenuIsCollapse(!menuStore.menuIsCollapse);
};
3. 标签页的显示与关闭逻辑
标签页的显示逻辑相对简单,主要通过监听侧边栏的点击事件,将当前页面的信息添加到 Pinia 管理的 tagList
中。
关闭逻辑稍微复杂一些,需要判断点击的标签是否是当前页面的标签,以及 tagList
中标签的数量,来决定是否需要进行路由跳转。
const handleClick = (item) => {
router.push(item.path);
};
const closeTab = (tag, index) => {
const tagIndex = menuStore.tagList.findIndex(item => item.path === tag.path);
menuStore.closeTag(tag);
if (route.path !== tag.path) {
return;
}
if (menuStore.tagList.length === 0) {
router.push('/dashboard');
} else {
if (tagIndex === menuStore.tagList.length - 1) {
router.push({ path: menuStore.tagList[tagIndex - 1].path });
} else {
router.push({ path: menuStore.tagList[tagIndex].path });
}
}
};
4. 样式与细节优化
Header 组件的样式使用了 SCSS,实现了简单的阴影效果和过渡动画,提升了用户体验。
{
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
// 其他样式...
}
通过细节优化,如调整标签页关闭时的逻辑判断和样式细节,使组件更加健壮和美观。
原文地址: Vue 3 Pinia ElementPlus 实现响应式 Header 组件
正文完