如何在uniapp中使用vue-router

安装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

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值