赞
踩
目录
(2)点击header内的菜单按钮实现aside菜单的展示和隐藏
使用vue3+ts+pinia+element-plus+echarts搭建一个通用的后台管理系统(没准后面会改成特定的功能)
header、aside是非路由组件,中间的部分用于放置不同的路由组件,例如home、user等
安装element-plus:
npm install element-plus --save
按需自动导入(推荐)
安装unplugin-vue-components
和 unplugin-auto-import
这两款插件:
npm install -D unplugin-vue-components unplugin-auto-import
把下列代码插入到 Vite
的配置文件中:
- // vite.config.ts
- import { defineConfig } from 'vite'
- import AutoImport from 'unplugin-auto-import/vite'
- import Components from 'unplugin-vue-components/vite'
- import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
-
- export default defineConfig({
- // ...
- plugins: [
- // ...
- AutoImport({
- resolvers: [ElementPlusResolver()],
- }),
- Components({
- resolvers: [ElementPlusResolver()],
- }),
- ],
- })
- import { createRouter, createWebHistory } from 'vue-router'
- const router = createRouter({
- history: createWebHistory(import.meta.env.BASE_URL),
- routes: [
- {
- path: '/',
- name: 'main',
- component: () => import('@/views/Main.vue'), // 路由懒加载
- // redirect: '/home',
- children: [
- {
- path: '/',
- name: 'home',
- component: () => import('@/views/Home/index.vue'),
- }
- ]
- },
-
- ]
- })
-
- export default router
- 在vies/main中:
- <!-- element-plus -->
- <el-container>
- <!-- 左侧 -->
- <el-aside width="200px">Aside</el-aside>
- <!-- 右侧 -->
- <el-container>
- <!-- 头部 -->
- <el-header>Header</el-header>
- <!-- 右侧 路由组件 -->
- <el-main>
- <router-view></router-view>
- </el-main>
- </el-container>
- </el-container>
- 在components/commonheader中:
- <el-header>
- <!-- 菜单图标 -->
- <div class="menu">
-
- </div>
- <!-- content -->
- <div class="header-content">
- 这里是heaeder
- </div>
- </el-header>
-
- 在views/main中:
- <!-- 头部 -->
- <el-header>
- <CommonHeader></CommonHeader>
- </el-header>
element-plus图标的引入
安装icon图标库:
npm install @element-plus/icons-vue
注册所有图标:
- // main.ts
-
- // 引入element图标库
- import * as ElementPlusIconsVue from '@element-plus/icons-vue'
-
- // 注册element图标
- for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
- app.component(key, component)
- }
使用图标:
- <!-- 菜单图标 -->
- <div class="menu">
- <el-icon>
- <Menu />
- </el-icon>
- </div>
使用element-plus里的下拉菜单完成头像和下拉菜单的展示
- <!-- content -->
- <div class="header-content">
- <!-- element-plus 下拉菜单 -->
- <el-dropdown>
- <span class="el-dropdown-link">
- <img class="head-portrait" src="../assets/头像.png" alt="">
- </span>
- <template #dropdown>
- <el-dropdown-menu>
- <el-dropdown-item>个人中心</el-dropdown-item>
- <el-dropdown-item>退出</el-dropdown-item>
- </el-dropdown-menu>
- </template>
- </el-dropdown>
- </div>
再使用flex布局将两个元素拉到左右两边
头像的图片是通过静态引入过来的,为了实现动态引入、便于更改的效果,这里使用new URL()来实现:URL() - Web API 接口参考 | MDN
- 在components/commonHeader中:
- // 用于动态引入图片的路径
- function getImgUrl(user: string) {
- // 第一个参数:绝对路径/相对路径
- // 第二个参数:base基准路径 当一个参数是相对路径时生效(默认undefined)
- return new URL(`../assets/images/${user}.png`, import.meta.url).href
- }
-
- <!-- 动态获取路径 -->
- <img class="head-portrait" :src="getImgUrl('user')" alt="">
import.meta.url指向的是当前组件的路径
暂时使用的菜单数据中,含有有子菜单的一级菜单和没有子菜单的一级菜单
- const menuList = reactive([
- {
- path: '/user',
- name: 'user',
- label: '用户管理',
- icon: 'user',
- url: 'UserManage/UserManage'
- },
- {
- label: '其他',
- icon: 'location',
- path: '/other',
- children: [
- {
- path: '/page1',
- name: 'page1',
- label: '页面1',
- icon: 'setting',
- url: 'Other/PageOne'
- },
- {
- path: '/page2',
- name: 'page2',
- label: '页面2',
- icon: 'setting',
- url: 'Other/PageTwo'
- }
- ]
- }
- ])
由于element-plus里有无子菜单的写法不太一致,因此将两种情况分开来,使用filter过滤成两个数组
- // 返回有二级菜单的一级菜单数组
- function hasChildren() {
- return menuList.filter((item: any) => {
- return item.children != undefined
- })
- }
- // 返回没有二级菜单的一级菜单数组
- function noChildren() {
- return menuList.filter((item: any) => {
- return item.children == undefined
- })
- }
再将数组数据动态渲染到页面
- <el-menu class="el-menu-vertical-demo" active-text-color="#303133">
- <!-- 用户管理 没有二级菜单-->
- <el-menu-item :index="menuLabel.path" v-for="(menuLabel, index) in noChildren()" :key="index">
- <el-icon>
- <!-- 自定义图标 -->
- <component class="icons" :is="menuLabel.icon"></component>
- </el-icon>
- <template #title>{{ menuLabel.label }}</template>
- </el-menu-item>
- <!-- 有二级菜单 -->
- <el-sub-menu :index="menuLabel.path" v-for="(menuLabel, index) in hasChildren()" :key="index">
- <template #title>
- <el-icon>
- <component class="icons" :is='menuLabel.icon'></component>
- </el-icon>
- <span>{{ menuLabel.label }}</span>
- </template>
- <!-- 子菜单 -->
- <el-menu-item-group>
- <el-menu-item :index="item.path" v-for="(item, index) in menuLabel.children" :key="index">
- <el-icon>
- <component class="icons" :is='item.icon'></component>
- </el-icon>
- <span>{{ item.label }} </span>
- </el-menu-item>
- </el-menu-item-group>
- </el-sub-menu>
- </el-menu>
涉及到兄弟组件commonHeader和commonAside的交互,可以使用pinia仓库实现数据的传递
header点击按钮,将是否菜单是否收缩的数据传给aside
- 在stores/menu.ts中:
- import { ref, computed } from 'vue'
- import { defineStore } from 'pinia'
-
- export const useMenuStore = defineStore('menu', () => {
- // 菜单是否折叠的状态 默认false
- let isCollapse = ref(false)
-
- function handleCollapse() {
- isCollapse.value = !isCollapse.value
- }
- return { isCollapse, handleCollapse }
- })
- 在components/commonheader中:
- import { useMenuStore } from '@/stores/Menu';
- // 解构赋值
- let { handleCollapse } = useMenuStore()
-
- <!-- 点击 改变showMenu状态 -->
- <el-button plain @click="handleCollapse()">
el-menu的collapse属性可以控制菜单的收缩
- 在component/commonAside中:
- import { useMenuStore } from '@/stores/Menu';
- import { storeToRefs } from 'pinia';
- // 解构赋值 storeToRefs使得数据保持响应式
- let { isCollapse } = storeToRefs(useMenuStore())
-
- <!-- 折叠width就变小 -->
- <el-aside :width="isCollapse ? '64px' : '180px'">
- <el-menu class="el-menu-vertical-demo" :collapse="isCollapse">
- ...
-
- .el-aside {
- transition: 0.6s ease-out;
- }
先配置路由
- routes: [
- {
- path: '/',
- name: 'main',
- component: () => import('@/views/Main.vue'), // 路由懒加载
- children: [
- {
- path: '/',
- name: 'home',
- component: () => import('@/views/Home/index.vue'),
- },
- {
- path: '/user',
- name: 'user',
- component: () => import('@/views/User.vue'),
- },
- {
- path: '/page1',
- name: 'page1',
- component: () => import('@/views/Page1.vue'),
- },
- {
- path: '/page2',
- name: 'page2',
- component: () => import('@/views/Page2.vue'),
- },
- ]
- },
- ]
在commonAisde中,点击对应菜单项,跳转到对应路由
- import router from '@/router';
- // 跳转到对应的路由
- function goRouter(item: any) {
- router.push({
- name: item.name,
- })
- }
-
- <el-menu-item :index="menuLabel.path" v-for="(menuLabel, index) in noChildren()"
- :key="index" @click="goRouter(menuLabel)">
- ...
- <el-menu-item :index="item.path" v-for="(item, index) in menuLabel.children"
- :key="index" @click="goRouter(item)">
- ...
调整reset.less、调整高度等等,就得到了最基础的框架样式
都暂时写成静态数据
- <el-row class="home">
- <!-- 左侧 user信息和table表格 -->
- <el-col :span="8" :gutter="20">
- <!-- user信息card -->
- <el-card class="info-card" shadow="hover" style="margin-top: 20px;">
- <template #header>
- <div class="user">
- <div class="image">
- <img src="../../assets/images/user.png" style="width: 100%;">
- </div>
- <div class="user-info">
- <div class="user-name">Admin</div>
- <div class="role">管理员</div>
- </div>
- </div>
- </template>
- <div class="login">
- <div class="login-info">上次登录的时间:<span>2023-11-7</span> </div>
- <div class="login-info">上次登录的地点:<span>成都</span></div>
- </div>
- </el-card>
- <!-- 表格数据card -->
- ...
- </el-col>
- <!-- 右侧 图表 -->
- <el-col :span="16">
- ...
- </el-col>
- </el-row>
先暂时使用静态数据
- // 左侧 table数据
- const tableData = [
- {
- name: 'oppo',
- todayBuy: 500,
- monthBuy: 3500,
- totalBuy: 22000
- },
- ...
- ]
- // 表头名称
- const tableLabel = {
- name: '品牌',
- todayBuy: '今日购买',
- monthBuy: '本月购买',
- totalBuy: '总购买'
- }
使用element-plus将数据渲染到表格里
- <!-- 表格数据card -->
- <el-card class="table-card" shadow="hover">
- <el-table :data="tableData" height="430" style="width: 100%;" stripe>
- <el-table-column v-for="(value, key) in tableLabel"
- :key="key" :prop="key" :label="value" />
- </el-table>
- </el-card>
二次封装axios
axios之前封装过了,直接照搬
配置代理的形式与vue2稍有区别
在vite.config.ts中:
- // vite.config.ts
- server: {
- //用来配置跨域
- host: '127.0.0.1',
- port: 5173,
- proxy: { // 配置代理
- '/api': {
- target: 'http://127.0.0.1:5050', //目标url
- changeOrigin: true // 支持跨域
- }
- }
- }
配置mockjs
和之前vue2项目里一样
建立mock文件夹,用于写mockServer和存储传送的data
- 在mock/mockServer中:
-
- // 引入mock.js
- import Mock from "mockjs";
- // 引入json
- // webpack默认图片和json数据格式对外暴露
- import tableData from '@/mock/tableData.json'
-
- // mock数据:第一个参数请求地址;第二个参数请求数据
- // 当发送ajax请求该地址时,浏览器拦截这条请求并将该数据返回
- Mock.mock('/mock/tabledata', { code: 200, data: tableData })
然后要在main.ts里引入才能生效***(不认真看忽略了这一步找了好久的错。。无语)
- // 引入mock (引入了才能使用mock)
- import '@/mock/mockServer.ts'
用于存储数据的json文件会报错
在tsconfig.app.ts中的include添加json文件路径
在在api文件夹中写mockRequests.ts
- // 该文件用于配置mock模拟axios
- import axios from "axios"
- import NProgress from 'nprogress'
- import 'nprogress/nprogress.css'
-
- // 配置不显示右上角的旋转进度条, 只显示水平进度条
- NProgress.configure({ showSpinner: false })
-
- const mockRequests = axios.create({
- baseURL: '/mock', // 设置公共路径
- timeout: 1000 * 10 // 设置请求超过时间 10s
- })
-
-
- // 添加请求拦截器
- mockRequests.interceptors.request.use(
- ...
- )
-
- // 添加响应拦截器
- mockRequests.interceptors.response.use(
- ...
- )
-
- export default mockRequests
使用线上mock
主要是用于临时渲染数据,不需要配置,比较方便
- let tableData = ref([])
- async function getData() {
- await getTableData().then(res => {
- // 使用ref才能实现这里操作的响应式 reactive无法检测这里的替换
- tableData.value = res.data
- })
- }
- onMounted(() => {
- getData()
- })
使用mock模拟请求账单countLIst,得到数据渲染即可
- [
- {
- "name": "今日支付订单",
- "value": 1234,
- "icon": "SuccessFilled",
- "color": "#2ec7c9"
- },
- {
- "name": "今日收藏订单",
- "value": 210,
- "icon": "StarFilled",
- "color": "#ffb980"
- },
- ...
-
- // 获取订单计数数据
- let countData: any = ref([])
- // 获取count数据
- async function getCData() {
- await getCountData().then(res => {
- countData.value = res.data
- })
- }
-
- <!-- 订单计数card -->
- <div class="count-all">
- <el-card class="count-card" shadow="hover" v-for="item in countData" :key="item.name">
- <el-icon>
- <component :is="item.icon" class="icons" :style="{ background: item.color }"></component>
- </el-icon>
- <div class="info">
- <p>{{ item.value }}</p>
- <p>{{ item.name }}</p>
- </div>
- </el-card>
- </div>
项目中引入echarts:
npm install echarts --save
获取dom元素:
图表的插入需要获取对应的dom元素,linechart.value即为需要的dom元素
- <div ref="linechart" style="height: 280px"> </div>
-
- const linechart = ref()
折线图、柱状图、饼图的配置项:
- // 关于echarts 表格的渲染部分 折线、柱状的配置项
- let xOptions = reactive({
- // 图例文字颜色
- textStyle: {
- color: "#333",
- },
- grid: {
- left: "20%",
- },
- // 提示框
- tooltip: {
- trigger: "axis",
- },
- xAxis: {
- type: "category", // 类目轴
- data: [],
- axisLine: {
- lineStyle: {
- color: "#17b3a3",
- },
- },
- axisLabel: {
- interval: 0,
- color: "#333",
- },
- },
- yAxis: [
- {
- type: "value",
- axisLine: {
- lineStyle: {
- color: "#17b3a3",
- },
- },
- },
- ],
- color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
- series: [],
- });
- // 饼图的配置项
- let pieOptions = reactive({
- tooltip: {
- trigger: "item",
- },
- color: [
- "#0f78f4",
- "#dd536b",
- "#9462e5",
- "#a6a6a6",
- "#e1bb22",
- "#39c362",
- "#3ed1cf",
- ],
- series: [],
- });
- // 获取发来的图表数据 进行echart初始化和渲染
- async function getchartData() {
- // 获取chart数据
- await getChartData().then(res => {
- let orderRes = res.data.orderData
- let userRes = res.data.userData
- let videoRes = res.data.videoData
- let series: any = []
- // 提取出键的数组
- const keyArray = Object.keys(orderRes.data[0])
-
- // 折线图的初始化和渲染
- // 每个品牌的数据
- keyArray.forEach((key) => {
- series.push({
- name: key,
- data: orderRes.data.map((item: any) => item[key]),
- type: "line",
- });
- });
- xOptions.xAxis.data = orderRes.date // x轴数据
- xOptions.series = series
- // orderData进行渲染
- let lineEcharts = echarts.init(linechart.value)
- lineEcharts.setOption(xOptions)
- }
- <!-- 折线图 -->
- <el-card style="height: 280px;margin-top: 20px;margin-left: 20px;" shadow="hover">
- <div ref="linechart" style="height: 280px"> </div>
- </el-card>
- // 获取chart数据
- await getChartData().then(res => {
- let orderRes = res.data.orderData
- let userRes = res.data.userData
- let videoRes = res.data.videoData
- let series: any = []
- // 提取出键的数组
- const keyArray = Object.keys(orderRes.data[0])
-
-
- // 柱形图的初始化和渲染
- series = [
- {
- name: "新增用户",
- data: userRes.map((item: any) => item.new),
- type: "bar",
- },
- {
- name: "活跃用户",
- data: userRes.map((item: any) => item.active),
- type: "bar",
- },
- ]
- xOptions.xAxis.data = userRes.map((item: any) => item.date);
- xOptions.series = series
- // userData进行渲染
- let userEcharts = echarts.init(userchart.value)
- userEcharts.setOption(xOptions)
- }
- <!-- 柱状图和饼图 -->
- <div class="graph" style="height: 260px;">
- <el-card style="height: 255px;" shadow="hover">
- <div ref="userchart" style="height: 245px"></div>
- </el-card>
- ...
- <div>
- // 获取发来的图表数据 进行echart初始化和渲染
- async function getchartData() {
- // 获取chart数据
- await getChartData().then(res => {
- let orderRes = res.data.orderData
- let userRes = res.data.userData
- let videoRes = res.data.videoData
- let series: any = []
- // 提取出键的数组
- const keyArray = Object.keys(orderRes.data[0])
-
- // 饼图的初始化和渲染
- series = [
- {
- data: videoRes,
- type: "pie",
- },
- ]
- pieOptions.series = series
- let videoEcharts = echarts.init(videochart.value)
- videoEcharts.setOption(pieOptions)
- })
- }
- <el-card style="height: 255px;padding-bottom: 10px;" shadow="hover">
- <div class="video-chart" ref="videochart" style="height: 245px"></div>
- </el-card>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。