朱丽叶

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

uni-app 使用uni-simple-router进行路由守卫

// 1. 安装依赖
// uni-read-pages 适用于读取page.json 文件中的路由信息
npm i uni-simple-router@2.0.7 uni-read-pages

// 2. 配置与初始化
// 2.1 根目录新建 vue.config.js 文件
const TransformPages = require('uni-read-pages')
const { webpack } = new TransformPages()
module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
	ROUTES: webpack.DefinePlugin.runtimeValue(() => {
	  const tfPages = new TransformPages({
	    includes: ['path', 'name', 'aliasPath', 'meta']
	  });
	  return JSON.stringify(tfPages.routes)
	}, true)
      })
    ]
  }
}

// 新建 router 配置文件
import { RouterMount, createRouter } from 'uni-simple-router';
import store from "@/store/index.js"

const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM,
  routerErrorEach: ({ type, msg }) => {
    console.log(type, msg);
    switch (type) {
      // APP退出应用
      case 3:
        // #ifdef APP-PLUS
        router.$lockStatus = false;
        uni.showModal({
          title: '提示',
          content: '您确定要退出应用吗?',
          success: function (res) {
            if (res.confirm) {
              plus.runtime.quit();
            }
          }
        });
        // #endif
        break;
      case 2:
      case 0:
        router.$lockStatus = false;
        break;
      default:
        break;
    }
  },
  routes: [...ROUTES]   // ROUTES 这个名称是webpack 中配置的名称
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
  if (to.meta && to.meta.currentNav) {
    store.commit('updateCurrentNav', to.meta.currentNav);
  }
  next()
});

export { router, RouterMount }

// 3 main.js导入router.js并挂载
import {router,RouterMount} from './router/index';

// #ifdef H5
	RouterMount(app,router,'#app')
// #endif

// #ifndef H5
	app.$mount(); //为了兼容小程序及app端必须这样写才有效果
// #endif

posted on   朱丽叶  阅读(2241)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示