1.创建uni项目(我自己用的node16)
vue create -p dcloudio/uni-preset-vue my-project
2.安装uni-simple-router 插件,最好是 2.0.7 版本。最新版可能会有BUG
yarn add uni-simple-router@2.0.7
3.安装uni-read-pages,需要配合vue.config.js可以获得pages.json的路径文件
yarn add uni-read-pages
4.根目录创建vue.config.js文件
const TransformPages = require('uni-read-pages')
const tfPages = new TransformPages()
module.exports = {
configureWebpack: {
plugins: [
new tfPages.webpack.DefinePlugin({
ROUTES: JSON.stringify(tfPages.routes)
})
]
}
}
5.router文件夹下面创建router.js文件
import { RouterMount, createRouter } from "uni-simple-router";
console.log("ROUTES", ROUTES);
const router = createRouter({
platform: process.env.VUE_APP_PLATFORM,
routes: [...ROUTES],
});
//全局路由前置守卫
router.beforeEach((to, from, next) => {
console.log(to,from);
//权限控制登录
if (to.meta.auth) {
console.log("需要登录");
if ("token") {
next();
} else {
console.log("请登录");
}
} else {
console.log("不需要登录");
}
next();
console.log("前置守卫" + JSON.stringify(to));
});
// 全局路由后置守卫
router.afterEach((to, from) => {
console.log("跳转结束");
});
export { router, RouterMount };
6.main.js引用
import Vue from "vue";
import App from "./App";
import "./uni.promisify.adaptor";
import { router, RouterMount } from "./router/router.js"; //路径换成自己的
Vue.use(router);
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
7.页面里使用
<template>
<view class="content">
<!-- #ifdef H5 -->
<view> H5端 </view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view> 小程序 </view>
<!-- #endif -->
<image class="logo" src="/static/logo.png"></image>
<view>
<text class="title" @click="goHome">{{ title }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
goHome() {
this.$Router.push({
path: "/pages/home/index",
query: { id: 1 }
});
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin: 200rpx auto 50rpx auto;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>