1、安装 (这里的版本是 2.x)
NPM安装
// 项目根目录执行命令行
npm install uni-simple-router
//以下是通过自动读取 pages.json 作为路由表的方式
npm install uni-read-pages
2、配置 vue.config.js
接着我们配置 vue.config.js
,如果你的项目根目录下没有 vue.config.js
那请你手动新增下。
// 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)
})
]
}
}
3、新建并写入 router.js
// /router/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) => {
//权限控制登录
if(to.meta.auth){
console.log("需要登录");
if("token"){//token存在 --继续
next();
}else{
console.log("请登录");
}
}else{
console.log("不需要登录");
next();
}
console.log("前置守卫"+JSON.stringify(to));
});
// 全局路由后置守卫
router.afterEach((to, from) => {
console.log('跳转结束')
})
export {
router,
RouterMount
}
4、在 main.js
引入 router.js
// main.js
import Vue from 'vue'
import App from './App'
import {router,RouterMount} from './router/router.js' //路径换成自己的
Vue.use(router)
App.mpType = 'app'
const app = new Vue({
...App
})
// 仅出现在 H5 平台下的代码
// #ifdef H5
RouterMount(app,router,'#app')
// #endif
// #ifndef H5
app.$mount(); //除了 H5 平台,其它平台均存在的代码 ,为了兼容小程序及app端必须这样写才有效果
// #endif
5、配置page.json
// pages.json
{
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app"
}
}, {
"path": "pages/list/list",
"meta": {
"auth": true //需要登录
},
"style": {
"navigationBarTitleText": "",
"enablePullDownRefresh": false
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},
"uniIdRouter": {}
}
参考文档:
- https://www.hhyang.cn/v2/tutorial/rgRoutes.html#配置-vue-config-js
- https://www.hhyang.cn/v2/tutorial/rgRoutes.html#安装