安装uni-simple-router
npm install uni-simple-router
初始化
以下是通过自动读取
pages.json
作为路由表的方式
安装uni-read-pages
npm install uni-read-pages
配置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']
});
return JSON.stringify(tfPages.routes)
}, true )
})
]
}
}
新建并导入router.js
// 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) => {
next();
});
// 全局路由后置守卫
router.afterEach((to, from) => {
console.log('跳转结束')
})
export {
router,
RouterMount
}
在main.js中引入router.js
import Vue from 'vue'
import App from './App'
import {router,RouterMount} from './router.js' //路径换成自己的
Vue.use(router)
App.mpType = 'app'
const app = new Vue({
...App
})
//v1.3.5起 H5端 你应该去除原有的app.$mount();使用路由自带的渲染方式
// #ifdef H5
RouterMount(app,router,'#app')
// #endif
// #ifndef H5
app.$mount(); //为了兼容小程序及app端必须这样写才有效果
// #endif
如何使用
pages.json
{
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"name":"index",
"aliasPath":"/",
"style": {
"navigationBarTitleText": "uni-app"
}
},
{
"path": "pages/login/login",
"name":"login",
"aliasPath":"/login",
"style": {
"navigationBarTitleText": "登录"
}
},
{
"path": "pages/register/register",
"name":"register",
"aliasPath":"/register",
"style": {
"navigationBarTitleText": "注册"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},
"uniIdRouter": {}
}
使用方式
this.$Router.push({ name: 'login'})
或者
this.$Router.push({ path: '/pages/login/login'})
使用this.$Router.push({ name: 'login'})的情况下会对H5端的url进行重写并进行覆盖
比如:
原来的路径:pages/login/login 跳转后:http://localhost:8080/#/pages/login/login
使用this.$Router.push({ name: 'login'})跳转后为http://localhost:8080/#/login
更多使用方式参考官方文档:uni-simple-router