uni-app

※前提条件:vue3 的uniapp开发

概要 [edit]

当某些页面需要登录,进入之前需要判断是否登录,如果没有登录则跳转到登录页。可以封装公共方法或混入实现,但是不太优雅,这时使用路由守卫实在是太方便了

安装 [edit]

安装uni-simple-router插件

npm install uni-simple-router

代码 [edit]

/main.js [edit]

import App from './App'
import Vue from 'vue'

import {router,RouterMount} from './router/router.js'
Vue.use(router)

// #ifndef VUE3

Vue.config.productionTip = false
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

/router/router.js [edit]

一定添加 path: '*' 否则:报错Error: / 路径无法在路由表中找到,检查跳转路径及路由表

// router/router.js
import {RouterMount, createRouter} from 'uni-simple-router';

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES, {
		path: '*'
		// 不需要配置跳转路由
		// redirect:(to)=>{  
		//    return {name:'404'}  
		//}  
	}, ]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	//权限控制登录
	// if(to.meta.auth){
	// 	console.log("需要登录");
	// 	if("token"){
	// 		next();
	// 	}else{
	// 		console.log("请登录");
	// 	}
	// }else{
	// 	console.log("不需要登录");
	//         next();
	// }

	console.log("前置守卫" + JSON.stringify(to));
	next();

});
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log('跳转结束')
})

export {
	router,
	RouterMount
}

/pages.json [edit]

对于h5端你必须在首页加上aliasPath并设置为 /

{
	"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
		{ //首页
			"path": "pages/index/index",
			"aliasPath": "/", //对于h5端你必须在首页加上aliasPath并设置为/
			"name": "index",
			"style": {
				"navigationBarTitleText": "uni-app"
			}
		},
                ...

/vue.config.js [edit]

注意:修改之后一定要重新编译,差量编译不会生效

// vue.config.js
const TransformPages = require('uni-read-pages')
const {
	webpack
} = new TransformPages()

module.exports = {
	configureWebpack: {
		plugins: [
			new webpack.DefinePlugin({
				ROUTES: webpack.DefinePlugin.runtimeValue(() => {
					console.log('打印一下');
					
					const tfPages = new TransformPages({
						//includes: ['path', 'name', 'aliasPath','meta']
						includes: ['path', 'name', 'aliasPath']
					});
					return JSON.stringify(tfPages.routes)
				}, true)
			})
		]
	}
}

Comment:



(画像の文字列を入力して下さい)

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS