生活不易、且行且珍惜。网站首页 程序人生
从零开始做网站5-前端vue项目全局路由和一些配置
发布时间:2022-05-20 21:09编辑:zj 阅读:文章分类:
网站互动QQ群:170915747
vue项目创建好了并且集成了基础的后台管理系统,调用后端接口也调通了。接下来就是开发后台管理系统的其他功能了,首先就是把相关路由和一些基础工具配置一下。
vue的全局路由配置,router/index.js
代码:
import {createRouter, createWebHashHistory, createWebHistory} from "vue-router"; import Home from "../views/admin/Home.vue"; import {authtoken} from "../api"; import {ElMessage} from "element-plus"; // 全局路由(无需嵌套上左右整体布局) const globalRoutes = [ {path: '/404', name: '404', meta: {title: '找不到页面'}, component: () => import (/* webpackChunkName: "404" */ '../views/common/404.vue')}, {path: '/403', name: '403', meta: {title: '没有权限'}, component: () => import (/* webpackChunkName: "403" */ '../views/common/403.vue')}, {path: "/login", name: "Login", meta: {title: '登录'}, component: () => import ( /* webpackChunkName: "login" */ "../views/common/Login.vue")}, {path: '/error/:msg?', name: 'error', meta: {title: '系统错误'}, component: () => import ( "../views/common/error.vue")} ] // 前台路由(不用登陆也能访问) const skipLoadMenusRoutes=[ {path: '/index', name: 'index', component: () => import (/* webpackChunkName: "index" */ "../views/index.vue"), meta: {title: '小甜崽'}}, {path: '/blog', name: 'blog', component: () => import (/* webpackChunkName: "blog" */ "../views/blog.vue"), meta: {title: '小甜崽|生活日记'}}, {path: '/about', name: 'about', component: () => import (/* webpackChunkName: "about" */ "../views/about.vue"), meta: {title: '小甜崽的自留地|关于我'}}, ] // 主入口路由(需嵌套上左右整体布局) const routes = [ {path: '/',redirect: '/index',meta: {title: 'ltBlog'}}, { path: "/home", name: "Home", component: Home, redirect: '/dashboard', children: [ {path: "/dashboard",name: "dashboard",meta: {title: '系统首页'},component: () => import ("../views/admin/Dashboard.vue")}, {path: "/articleList",name: "articleList",meta: {title: '文章管理'},component: () => import ( /* webpackChunkName: "articleList" */ "../views/admin/ArticleList.vue")}, {path: "/publishArticle", name: "publishArticle", meta: {title: '文章发布'}, component: () => import ( /* webpackChunkName: "publishArticle" */ "../views/admin/AddArticle.vue")}, {path: "/moodList", name: "moodList", meta: {title: '心情说说'}, component: () => import ( /* webpackChunkName: "moodList" */ "../views/admin/Mood.vue")}, {path: "/albumList", name: "albumList", meta: {title: '相册管理'}, component: () => import ( /* webpackChunkName: "albumList" */ "../views/admin/Album.vue")}, {path: "/photoList", name: "photoList", meta: {title: '发布照片'}, component: () => import ( /* webpackChunkName: "photoList" */ "../views/admin/Photo.vue")}, {path: "/fLinkList", name: "fLinkList", meta: {title: '友链管理'}, component: () => import ( /* webpackChunkName: "fLinkList" */ "../views/admin/FLink.vue")}, {path: '/editor', name: 'editor', meta: {title: '富文本编辑器'}, component: () => import (/* webpackChunkName: "editor" */ '../views/admin/Editor.vue')} ] } ]; const router = createRouter({ history: createWebHistory(), //createWebHashHistory routes:routes.concat(globalRoutes).concat(skipLoadMenusRoutes) }); /** * 动态加载菜单流程 * 1、判断当前是否加载菜单 * 2、出现在 globalRoutes 和 skipLoadMenusRoutes 中的路由不需要加载动态菜单。 */ router.beforeEach((to, from, next) => { //输入不存在的路由则直接返回404 if(to.matched.length === 0){ // from.path ? next({name: from.name}) : next('/404') next('/404') return; } document.title = `${to.meta.title} | ltBlog`; const token = localStorage.getItem('ms_token'); let currentRouteType = fnCurrentRouteType(to, globalRoutes) if (currentRouteType !== 'global') { currentRouteType = fnCurrentRouteType(to, skipLoadMenusRoutes) } //请求的路由在【不用登陆也能访问路由数组】中,则不用跳转到登录页 if (currentRouteType === 'global') { next(); } else { //如果路由为空,并且不在【不用登陆也能访问路由数组】中 则跳转到登录页 if(!token){ next('/login'); }else{ //每次跳转路由都去判断token是否有效 authtoken().then((res) => { //如果token无效或者已过期 则跳转到登录页 if(res.success === false){ localStorage.removeItem("ms_token"); ElMessage.error("登录过期,请重新登录"); next('/login'); }else{ next(); } }); } } }); /** * 判断当前路由类型, global: 全局路由, main: 主入口路由 * 判断逻辑: * 1、如果目标路由的name 或路径 出现在 globalRoutes 参数中 * @param {*} route 当前路由 * @param {*} globalRoutes 路由匹配数组 */ function fnCurrentRouteType(route, globalRoutes = []) { var temp = [] for (var i = 0; i < globalRoutes.length; i++) { if (route.path === globalRoutes[i].path || (route.name !== undefined && route.name === globalRoutes[i].name)) { return 'global' } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) { temp = temp.concat(globalRoutes[i].children) } } return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'Home' } export default router;
vue项目中 页面组件懒加载 使用webpackChunkNmae
在路由中使用
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
来实现组件的懒加载 这种配置会生产一个about.[hash].js
对于优化首屏很有帮助, 但对于内部页面会有一点损失,比较资源不会一次加载到位的。
使用 Vuex + Axios 方式进行网络请求
axios 是一个网络请求构架,官方推荐使用这种方式进行 http 的请求。
1) 在 utils 包下封装一个请求工具类 request.js
import axios from 'axios'; //import { MessageBox, Message } from 'element-ui' const service = axios.create({ // process.env.NODE_ENV === 'development' 来判断是否开发环境 // easy-mock服务挂了,暂时不使用了 baseURL: 'http://localhost:8080', timeout: 5000 }); /** * 请求拦截 */ service.interceptors.request.use( config => { return config; }, error => { console.log(error); return Promise.reject(); } ); /** * 响应拦截 */ service.interceptors.response.use( response => { if (response.status === 200) { return response.data; } else { Promise.reject(); } }, error => { console.log(error); return Promise.reject(); } ); export default service;
2) 请求接口 API
在 api 文件夹下,创建一个index.js
import request from '../utils/request'; //查询文章列表 export const fetchData = query => { return request({ url: 'http://localhost:8080/article/getList', method: 'get', params: query }); };
设置全局变量
main.js import {createApp} from 'vue' const app = createApp(App) // 挂载全局 app.config.globalProperties.$http = httpRequest // ajax请求方法
使用全局变量
import { ref, reactive, getCurrentInstance } from "vue"; const proxy = getCurrentInstance()?.appContext.config.globalProperties.$http; proxy({ method:'get', url:'/article/getList', }).then(res => { console.log(res) tableData.value = res; pageTotal.value = res.pageTotal || 50; })
注意:使用的是vue3.0
一些基础配置就好了,后面就是写接口,然后前端样式,后台主要就是列表的增删改查功能了。
#去评论一下
标签:#Springboot#Vue
版权声明:本博客的所有原创内容皆为作品作者所有
转载请注明:来自ZJBLOG 链接:www.zjhuiwan.cn


「万物皆有时,比如你我相遇」
感谢大佬打赏【请选择支付宝或微信,再选择金额】
使用微信扫描二维码完成支付
