uni-app集成uni-simple-router、uni-read-pages插件自动读取page.json文件实现路由管理(无需手动配置路由表)

  1. npm 下载uni-simple-router、uni-read-pages插件
"uni-read-pages": "^1.0.5",
"uni-simple-router": "^2.0.5"
  1. 根目录新建router.js
import {
	RouterMount,
	createRouter
} from 'uni-simple-router';

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES]
});
//全局路由前置守卫
router.beforeEach((to, from, next) => {
	console.log(to, from);
	
	next();
});
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log('跳转结束')
})

export {
	router,
	RouterMount
}

  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','icon']  //需要获取包涵的字段, 跟pages.json的字段对应
					});
					return JSON.stringify(tfPages.routes)
				}, true )
			})
		]
	}
}
  1. 在main.js引入router.js
import Vue from 'vue'
import App from './App'
import {
	router,
	RouterMount
} from './router.js'
import store from "@/store/index.js"
import filters from "./filters";
Vue.use(router)
import uView from "uview-ui";
Vue.use(uView);

for (let key in filters) {
	Vue.filter(key, filters[key])
}

Vue.config.productionTip = false
Vue.prototype.$store = store

App.mpType = 'app'

const app = new Vue({
	store,
	...App
})


//v1.3.5起 H5端 你应该去除原有的app.$mount();使用路由自带的渲染方式
// #ifdef H5
RouterMount(app, router, '#app')
// #endif

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

  1. vue页面获取路由信息
created() {
	console.log('ROUTES=---', ROUTES)  // 获取pages.json的全部路由数据
},

参考链接:
https://github.com/SilurianYang/uni-simple-router
https://github.com/SilurianYang/uni-read-pages

你可能感兴趣的:(uni-app,json)