官网:uni-simple-router
第一步插件安装命令:
cnpm install uni-simple-router
cnpm install uni-read-pages
第二步项目根目录创建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']
});
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 App from './App'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
import {router,RouterMount} from './router.js' //路径换成自己的
Vue.use(router)
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif
//v1.3.5起 H5端 你应该去除原有的app.$mount();使用路由自带的渲染方式
// #ifdef H5
RouterMount(app,router,'#app')
// #endif
// #ifndef H5
app.$mount(); //为了兼容小程序及app端必须这样写才有效果
// #endif