UNI-APP_uni-simple-router的快速上手(路由,nui路由拦截)

官网文档:http://www.hhyang.cn/src/router/start/quickstart.html

安装插件

npm安装命令:npm install uni-simple-router
下载好后会多出这个文件夹
在这里插入图片描述

初始化

在项目的根目录下创建如下用红框框住的文件夹及文件
在这里插入图片描述
modules目录下的index.js内容如下(这个文件主要作用是将所有路由整合成一个数组)

// router/modules/index.js
const files = require.context('.', false, /\.js$/)
const modules = []

files.keys().forEach(key => {
    
    
  if (key === './index.js') return
  const item = files(key).default
  modules.push(...item)
})

export default modules

在modules目录下home.js文件,作用是根据不同的路由分类,添加更多模块

 // router/modules/home.js
const home = [
	{
    
    
        //注意:path必须跟pages.json中的地址对应,最前面别忘了加'/'哦
      path: '/pages/login/login',
      name: 'login',
        meta: {
    
    
	        title: '登陆',
	    },
    }
]
export default home 

router下的index.js配置如下

// router/index.js

import modules from './modules'
import Vue from 'vue'
//这里仅示范npm安装方式的引入,其它方式引入请看最上面【安装】部分
import Router from 'uni-simple-router'

Vue.use(Router)
//初始化
const router = new Router({
    
    
    routes: [...modules]//路由表
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
    
    
	console.log("全局路由前置守卫")
	 next()
})
// 全局路由后置守卫
router.afterEach((to, from) => {
    
    
	console.log("全局路由后置守卫")
})
export default router;

main.js引入

// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import {
    
     RouterMount } from 'uni-simple-router'

App.mpType = 'app'

const app = new Vue({
    
    
	...App
})
//v1.3.5起 H5端 你应该去除原有的app.$mount();使用路由自带的渲染方式
// #ifdef H5
	RouterMount(app,'#app');
// #endif

// #ifndef H5
	app.$mount(); //为了兼容小程序及app端必须这样写才有效果
// #endif

然后启动我们的项目进入页面就能看到进入路由了
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44599931/article/details/108799503