持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情
vue2支持,vue3不行:
需要安装uni-read-pages和uni-simple-router,通过两个插件实现如同vue的router的效果,这样就可以进行路由拦截
package.json
{
"name": "uniapp",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {},
"dependencies": {
"uni-read-pages": "^1.0.5",
"uni-simple-router": "^2.0.2"
}
}
pages.json:
{
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}
}
vue.config.js
其中includes可以设置自定义的一些参数,具体文案请看下文链接
const TransformPages = require('uni-read-pages')
const {
webpack
} = new TransformPages()
let pluginsDev = new webpack.DefinePlugin({
ROUTES: webpack.DefinePlugin.runtimeValue(() => {
const tfPages = new TransformPages({
includes: ['path', 'name', 'aliasPath']
});
return JSON.stringify(tfPages.routes)
}, true)
})
console.log(ROUTES,'---ROUTES---')
module.exports = {
configureWebpack: {
},
chainWebpack: (config) => {
config.plugins.push(pluginsDev)
// 发行或运行时启用了压缩时会生效
config.optimization.minimizer('terser').tap((args) => {
const compress = args[0].terserOptions.compress
// 非 App 平台移除 console 代码(包含所有 console 方法,如 log,debug,info...)
compress.drop_console = true
compress.pure_funcs = [
'__f__', // App 平台 vue 移除日志代码
// 'console.debug' // 可移除指定的 console 方法
]
return args
})
}
}
根目录创建: router->index.js:
// router.js
import {
RouterMount,
createRouter
} from 'uni-simple-router';
// 创建路由表
const router = createRouter({
// vue-cli创建项目的相关环境变量文件里面的变量,可能是区分平台使用,不是太重要。
platform: process.env.VUE_APP_PLATFORM,
// 路由信息
routes: [...ROUTES]
});
//全局路由前置守卫
router.beforeEach((to, from, next) => {
console.log(to, from,'--to, from, next---')
next()
// next({
// path: '',
// NAVTYPE: 'push'
// });
});
// 全局路由后置守卫
router.afterEach((to, from) => {
console.log('跳转结束')
})
export {
router,
RouterMount
}
mian.js:
import App from './App'
// 路由
import {
router,
RouterMount
} from './router/index.js';
import Vue from 'vue'
// 路由
Vue.use(router)
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
// #ifdef H5
RouterMount(app, '#app');
// #endif
app.$mount()