Commit 3a370151 by 前端

init

1 parent 0f405819
Showing 217 changed files with 4565 additions and 333 deletions
unpackage
node_modules
uview-ui
.DS_Store
node_modules
/unpackage
\ No newline at end of file \ No newline at end of file
/node_modules
/unpackage
/.idea
/.vscode
/.DS_Store
/.hbuilderx
\ No newline at end of file \ No newline at end of file
...@@ -6,10 +6,6 @@ ...@@ -6,10 +6,6 @@
{ {
"launchtype" : "local" "launchtype" : "local"
}, },
"h5" :
{
"launchtype" : "local"
},
"mp-weixin" : "mp-weixin" :
{ {
"launchtype" : "local" "launchtype" : "local"
......
<script> <script>
import common from './utils/wxApplet/common.js'
export default { export default {
onLaunch: function() { onLaunch: function() {
console.log('App Launch') console.log('>>>>>>>>>>>>>>>会话开始<<<<<<<<<<<<<<')
common.wxLogin();
}, },
onShow: function() { onShow: function() {},
console.log('App Show') onHide: function() {}
},
onHide: function() {
console.log('App Hide')
}
} }
</script> </script>
<style> <style lang="scss">
</style> @import "uview-ui/index.scss";
page {
background: $u-bg-color;
color: $u-main-color;
font-size: 28rpx;
height: 100%;
min-height: 100%;
}
view,
navigator,
image,
text,
scroll-view,
swiper,
swiper-item,
input,
textarea,
button {
box-sizing: border-box;
}
/* 文字避头尾法则 */
.btw {
table-layout: fixed;
word-wrap: break-word;
word-break: normal;
text-align: justify;
text-justify: inter-ideograph;
}
.bg-white {
background: #fff;
}
.font-weight {
font-weight: bold;
}
.u-flex-center {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
button {
margin: 0;
padding: 0;
line-height: 1.5;
font-size: 28rpx;
background-color: transparent;
border-radius: 0;
position: relative;
}
button::after {
border: none;
}
// 指定按钮按下去的样式类
.button-hover {
transform: translate(1rpx, 1rpx);
}
</style>
\ No newline at end of file \ No newline at end of file
MIT License
Copyright (c) 2020 www.uviewui.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
\ No newline at end of file \ No newline at end of file
# uniapp-uView
#### 介绍
基于 uView1.8.8 封装的一套基础模版,开箱即用,可直接开始快速开发业务需求~
```
想用uview2.0版本的去uview2的分支上下载
```
## 项目地址
module.exports = {
// 请求域名 格式:https://xxx.xxx.com
HTTP_REQUEST_URL: 'http://127.0.0.1:8000/api',
// 阿里云oss域名 格式:https://xxx.oss-cn-xxx.aliyuncs.com
OSS_DOMAIN: '',
// 文件直传到阿里云oss时需用到
ACCESSKEYID: '',
ACCESSKEYSECRET: '',
// 与后端约定的token字段名
TOKEN_NAME: 'Authorization'
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>
import App from './App'
// #ifndef VUE3
import Vue from 'vue' import Vue from 'vue'
import App from './App'
import config from '@/config.js'
import store from '@/store';
Vue.config.productionTip = false Vue.config.productionTip = false
App.mpType = 'app' App.mpType = 'app'
Vue.prototype.$ossDomain = config.OSS_DOMAIN;
import './router'
// 引入uView
import uView from 'uview-ui'
Vue.use(uView);
const app = new Vue({ const app = new Vue({
...App store,
...App
}) })
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif
\ No newline at end of file \ No newline at end of file
// http拦截器
import httpInterceptor from '@/utils/http.interceptor.js'
Vue.use(httpInterceptor, app)
// http接口API集中管理
import httpApi from '@/utils/http.api.js'
Vue.use(httpApi, app)
app.$mount()
{ {
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages "easycom": {
"^u-(.*)": "@/uview-ui/components/u-$1/u-$1.vue"
},
"pages": [
{ {
"path": "pages/index/index", "path": "pages/index/index",
"style": { "style": {
"navigationBarTitleText": "录音" "navigationBarTitleText": "uView-index"
}
},
{
"path": "pages/login/login",
"style": {
"navigationBarTitleText": "登录"
} }
} }
,{ ],
"path" : "pages/book/book",
"style" :
{
"navigationBarTitleText": "",
"enablePullDownRefresh": false
}
}
],
"globalStyle": { "globalStyle": {
"navigationBarTextStyle": "black", "navigationBarTextStyle": "black",
"navigationBarTitleText": "录音", "navigationBarTitleText": "生意助手",
"navigationBarBackgroundColor": "#F8F8F8", "navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8" "backgroundColor": "#F8F8F8"
} }
......
No preview for this file type
<!-- pages/record/record.vue -->
<template> <template>
<view class="main-box"> <view class="content">
<button @tap="startRecord">开始录音</button> <image class="logo" src="/static/logo.png"></image>
<button @tap="endRecord">停止录音</button> <view class="text-area">
<button @tap="playVoice">播放录音</button> <text class="title">
<button @tap="uploadAudio">上传录音</button> uView - 多平台快速开发的UI框架
<!-- <view class="book-box"> </text>
<view class="box-item" @tap="jump(item)" v-for="(item,index) in boxList"> </view>
<view class="book-image"> <view class="button-demo">
<image src="../../static/logo.png"></image> <u-button type="primary" plain @click="go()">登录</u-button>
</view>
<text>{{item.text}}</text>
</view>
</view> -->
<view class="footer-box">
<button class="end-btn" @tap="handleEnd">完成接待</button>
</view> </view>
</view> </view>
</template> </template>
<script> <script>
import ossClient from '../../utils/oss.js';
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
export default { export default {
data() { data() {
return { return {
boxList: [{ title: 'Hello',
text: '问界交车告知书'
}, {
text: '商城延保价格明细'
}, {
text: '保修升级告知书'
}, {
text: '问界三包政策'
}, {
text: '历史成交客户'
}, {
text: '整车质保升级政策'
}],
voicePath: ''
} }
}, },
onLoad() { onLoad() {
let self = this;
recorderManager.onStop(function(res) {
console.log('recorder stop' + JSON.stringify(res));
self.voicePath = res.tempFilePath;
self.getBase64(self.voicePath)
});
}, },
methods: { methods: {
jump(item) { go() {
uni.navigateTo({ this.$Router.push({name:'login'})
url: `/pages/book/book?text=${item.text}`
})
},
getBase64(tempFilePath) {
const self = this
uni.getFileSystemManager().readFile({
filePath: tempFilePath,
encoding: 'base64',
success(data) {
self.base64ToBlob(data.data);
},
fail(error) {
console.error(error);
}
})
},
base64ToBlob(base64String) {
const byteCharacters = atob(base64String);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: 'MIME' });
},
putObject: async function(data) {
try {
// 填写Object完整路径。Object完整路径中不能包含Bucket名称。
// 您可以通过自定义文件名(例如exampleobject.txt)或文件完整路径(例如exampledir/exampleobject.txt)的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
// data对象可以自定义为file对象、Blob数据或者OSS Buffer。
const options = {
meta: {
temp: "demo"
},
mime: "json",
headers: {
"Content-Type": "text/plain"
},
};
const result = await ossClient.put("examplefile.txt", data, options);
console.log(result);
uni.showLoading({title:result})
} catch (e) {
uni.showLoading({title:e})
console.log(e);
}
},
startRecord() {
recorderManager.start();
},
endRecord() {
console.log('录音结束');
recorderManager.stop();
},
playVoice() {
console.log('播放录音');
if (this.voicePath) {
innerAudioContext.src = this.voicePath;
innerAudioContext.play();
}
},
uploadAudio() {
uni.uploadFile({
url: 'http://192.168.1.127:5001/upload',
filePath: this.voicePath,
name: 'file',
formData: {
key,
policy,
OSSAccessKeyId: ossAccessKeyId,
signature,
// 'x-oss-security-token': securityToken // 使用STS签名时必传。
},
success: function(res) {
console.log(res)
},
fail: function(err) {
// 处理上传失败的情况
}
});
} }
// uploadAudio() {
// uni.uploadFile({
// url: 'http://192.168.1.127:5001/upload',
// filePath: this.voicePath,
// fileType: 'audio',
// fileName: '123',
// name: 'file',
// success: function(res) {
// console.log(res)
// },
// fail: function(err) {
// // 处理上传失败的情况
// }
// });
// }
} }
} }
</script> </script>
<style scoped lang="scss">
.main-box {
padding: 20rpx;
.book-box {
display: flex;
flex-wrap: wrap;
gap: 30rpx 12rpx;
text-align: center;
text { <style lang="scss" scoped>
font-size: 14rpx; .content {
line-height: 23rpx; display: flex;
color: #292D33; flex-direction: column;
} align-items: center;
justify-content: center;
padding: 40rpx;
}
.book-image { .logo {
image { height: 200rpx;
width: 162rpx; width: 200rpx;
height: 162rpx; margin-top: 100rpx;
border-radius: 8rpx; margin-left: auto;
} margin-right: auto;
margin-bottom: 50rpx;
}
} .text-area {
} display: flex;
justify-content: center;
} }
.footer-box { .title {
position: fixed; font-size: 28rpx;
bottom: 0rpx; color: $u-content-color;
left: 0rpx; }
padding: 10rpx;
width: 100%;
box-sizing: border-box;
.end-btn { .button-demo {
height: 40rpx; margin-top: 80rpx;
background: #2C66F7;
border-radius: 20rpx;
font-size: 16rpx;
color: #FFFFFF;
text-align: center;
line-height: 40rpx;
width: 50%;
}
} }
</style> </style>
<template>
<view class="v1">
<view class="avatarUrl">
<image v-if="vuex_userInfo" :src="vuex_userInfo.avatar_url" mode="widthFix"></image>
<open-data v-else type="userAvatarUrl"></open-data>
</view>
<view class="content">
<view class="v2"></view>
<view v-if="isShowUserInfo" class="v3">申请获得以下权限</view>
<view v-if="isShowUserInfo" class="v4">获取你的公开信息(昵称、头像等)</view>
<view v-if="!isShowUserInfo" class="v3">手机号快捷登录</view>
<view v-if="!isShowUserInfo" class="v4">未注册的手机号登录后将自动注册</view>
<button v-if="isShowUserInfo" @click="getUserProfile" class="u-reset-button u-flex u-row-center btn1" type="default">
<u-icon size="40" name="weixin-fill"></u-icon>
<text class="u-margin-left-10">获取微信昵称头像</text>
</button>
<button v-else open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="u-reset-button u-flex u-row-center btn1" type="default">
<u-icon size="40" name="weixin-fill"></u-icon>
<text class="u-margin-left-10">微信手机号快捷登录</text>
</button>
<button @click="noSignIn" class="u-reset-button u-flex u-row-center btn2" type="default">暂不登录</button>
</view>
</view>
</template>
<script>
import common from '@/utils/wxApplet/common.js'
export default {
data() {
return {
// 是否显示获取头像昵称按钮
isShowUserInfo: this.$store.state.vuex_userInfo ? false : true,
}
},
methods: {
// 获取昵称、头像等信息
getUserProfile() {
common.getUserProfile().then(res => {
if (res) {
this.isShowUserInfo = false;
}
})
},
// 手机号快捷登录
getPhoneNumber(e) {
common.getPhoneNumber(e).then(res => {
if (res) {
uni.showToast({
title: '登录成功',
icon: 'success'
})
setTimeout(() => {
this.noSignIn();
}, 1300)
}
})
},
// 暂不登录
noSignIn() {
let pages = getCurrentPages()
// 没有上级页面,直接返回首页
if (pages.length == 1) {
uni.reLaunch({
url: '/pages/index/index'
})
} else {
uni.navigateBack()
}
}
}
}
</script>
<style lang="scss" scoped>
.v1 {
width: 100%;
height: 100%;
overflow: hidden;
background: #ffffff;
padding-top: 100rpx;
}
.avatarUrl {
width: 200rpx;
margin: 0 auto;
height: 200rpx;
border-radius: 50%;
overflow: hidden;
border: 4rpx solid #fff;
box-shadow: 0rpx 0rpx 10rpx $u-light-color;
image {
width: 200rpx;
}
}
.content {
width: 84%;
margin: 0 auto;
}
.v2 {
width: 100%;
margin-top: 70rpx;
height: 2rpx;
background: $u-border-color;
}
.v3 {
margin-top: 50rpx;
font-weight: 600;
font-size: 34rpx;
color: $u-main-color;
}
.v4 {
margin: 30rpx 0 80rpx 0;
font-size: 28rpx;
color: $u-tips-color;
}
.btn1 {
margin-bottom: 24rpx;
background: #808003;
color: #fff;
height: 90rpx;
border-radius: 90rpx;
}
.btn2 {
background: $u-border-color;
color: #fff;
height: 90rpx;
border-radius: 90rpx;
}
</style>
# uni-simple-router
> 一个更为简洁的[Vue-router](https://router.vuejs.org/zh/),专为 [uni-app](https://uniapp.dcloud.io/) 量身打造
## 介绍
`uni-simple-router` 是专为 [uni-app](https://uniapp.dcloud.io/) 打造的路由器。它与 [uni-app](https://uniapp.dcloud.io/) 核心深度集成,使使用 [uni-app](https://uniapp.dcloud.io/) 轻松构建单页应用程序变得轻而易举。功能包括:
* `H5端` 能完全使用 `vue-router` 进行开发。
* 模块化,基于组件的路由器配置。
* 路由参数,查询,通配符。
* `H5端` 查看由 `uni-simple-router` 过渡系统提供动力的过渡效果。
* 更细粒度的导航控制。
* `H端`自动控制活动的CSS类链接。
* 通配小程序端、APP端、H5端。
开始使用 [查看文档](http://hhyang.cn),或 [使用示例](https://github.com/SilurianYang/uni-simple-router/tree/master/examples)(请参见下面的示例)。
## 问题
在提交问题的之前,请确保阅读 [“问题报告清单”](https://github.com/SilurianYang/uni-simple-router/issues/new?assignees=&labels=&template=bug_report.md&title=) 。不符合准则的问题可能会立即被解决。
## 贡献
提出拉取请求之前,请务必先阅读 [查看文档](http://hhyang.cn)(请参见下面的示例)。。
## 变更日志
[发行说明](https://github.com/SilurianYang/uni-simple-router/releases) 中记录了每个发行版的详细信息更改。
## 特别感谢
特别感谢 [markrgba](https://github.com/markrgba) 一直以来对文档和相关测试的维护。
## 技术交流
<a target="_blank" href="//shang.qq.com/wpa/qunwpa?idkey=0f4d7f38e5d15dd49bf7c3032c80ed3f54ecfa3dd800053d6ae145c869f9eb47"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="uni-app 插件" title="uni-app 插件"></a>
import {
proxyLaunchHook, beforeBackHooks, beforeTabHooks, backApiCallHook,
} from './hooks';
import { Global, uniAppHook } from '../helpers/config';
import { assertCanBack } from './util';
import { warn } from '../helpers/warn';
/**
* 重写掉uni-app的 uni.getLocation 和 uni.chooseLocation APi
* @param {Object} Router 当前路由对象
*/
export const rewriteUniFun = function (Router) {
const oldSwitchTab = uni.switchTab; // 缓存 跳转到 tabBar 页面
uni.switchTab = function ({ url, ...args }, normal = false) {
if (normal === true || uniAppHook.pageReady === false) { // 调用原始的uni-app api
oldSwitchTab({
url,
...args,
});
} else {
if (uniAppHook.pageReady) { // 只有在路由守卫等 处理完所有操作后才能触发
const { path } = Router.$Route; // 获取当前路径
if (path == url) { // 路径相同不执行
return warn(`当前跳转路径:${url} 已在本页面无须跳转`);
}
beforeTabHooks.call(Router, url.substring(1)); // 不要 /
} else {
warn('路由守卫正在忙碌中 不允许执行 ‘uni.switchTab’');
}
}
};
};
/**
* 对当前app做一个动画页面 用来过渡首次next 等待时间过长的尴尬
* @param {Object} Router 当前路由对象
*/
export const registerLoddingPage = function (Router) {
const { loddingPageHook, loddingPageStyle } = Router.CONFIG.APP; // 获取app所有配置
const view = new plus.nativeObj.View('router-loadding', {
top: '0px',
left: '0px',
height: '100%',
width: '100%',
...loddingPageStyle.call(Router),
});
loddingPageHook.call(Router, view); // 触发等待页面生命周期
};
/**
* 移除当前 页面上 非router 声明的 onBackPress 事件
* @param {Object} page 当前 vue 组件对象
* @param {Object} options 当前page对象的 $options
* 修复 https://github.com/SilurianYang/uni-simple-router/issues/106
*/
export const removeBackPressEvent = function (page, options) {
const isBack = assertCanBack(page);
if (isBack) { // 可返回
options.onBackPress = [options.onBackPress[0]]; // 路由混入的都干掉
}
};
/**
* 判断当前页面是否需要拦截返回
*
* @param {Object} page 当前 vue 组件对象
* @param {Object} options 当前 vue 组件对象下的$options对象
* @param {Array} args 当前页面是点击头部返回还是底部返回
* 修复 https://github.com/SilurianYang/uni-simple-router/issues/66
*
* this 为当前 Router 对象
*/
export const pageIsHeadBack = function (page, options, args) {
if (args[0].from == 'navigateBack') { // 调用api返回
if (Global.LockStatus) { // 正在跳转的时候 返回按键按的太快啦
warn('当前页面正在处于跳转状态,请稍后再进行跳转....');
return true;
}
Global.LockStatus = true; // 设置为锁住状态
backApiCallHook.call(this, options, args);
return true;
}
const isBack = assertCanBack(page);
if (isBack) { // 可返回
if (Global.LockStatus) { // 正在跳转的时候 返回按键按的太快啦
warn('当前页面正在处于跳转状态,请稍后再进行跳转....');
return true;
}
Global.LockStatus = true; // 设置为锁住状态
beforeBackHooks.call(this, options, args);
return true;
}
return false;
};
/**
* 开始初始化app端路由配置
*
* @param {Object} Router
*
* this 为当前 page 对象
*/
export const appInit = function (Router) {
proxyLaunchHook.call(this);
const { holdTabbar } = Router.CONFIG.APP;
if (holdTabbar) { // 开启tab拦截时
rewriteUniFun(Router);
}
registerLoddingPage(Router);
};
import { methods, baseConfig, Global } from '../helpers/config';
import { noop, formatURLQuery } from '../helpers/util';
let stop = null;
/**
* @param {Object} finalRoute 格式化后的路由跳转规则
* @param {Object} NAVTYPE 需要调用的跳转方法
*/
const uniPushTo = function (finalRoute, NAVTYPE) {
return new Promise((resolve) => {
const query = formatURLQuery(`?${finalRoute.uniRoute.query}`);
const { APP } = baseConfig;
const { url } = finalRoute.uniRoute;
stop = setTimeout(() => {
resolve(url);
resolve = noop; // 执行完了就没了 确保不会被下一次执行
Global.LockStatus = false; // 跳转完成解锁状态
}, APP.switchPageOutTime);
uni[methods[NAVTYPE]]({
url: url + query,
...finalRoute.route.animation,
complete: () => {
clearTimeout(stop);
resolve(url);
resolve = noop; // 执行完了就没了 确保不会被下一次执行
Global.LockStatus = false; // 跳转完成解锁状态
},
}, true); // 这里传递true 主要是兼容重写 uni.switchTab
});
};
export default uniPushTo;
import { err } from '../helpers/warn';
import { copyObject, parseQuery } from '../helpers/util';
import { Global, route as mergeRoute } from '../helpers/config';
/**
* 触发指定生命钩子
* @param {Array} funList //需要执行的方法列表
* @param {Object} args //触发生命钩子传递的参数
*/
export const callAppHook = function (funList = [], args) {
for (let i = 0; i < funList.length; i += 1) {
funList[i].call(this, args);
}
};
/**
* @param {Number} index //需要获取的页面下标 -2:表示获取最后一个即当前页面 -1:表示全部 -3:当前页面的前一个页面
* @param {Boolean} all //是否获取全部的页面
*/
export const getPages = function (index = -1, all) {
const pages = getCurrentPages(all);
if (index === -1) {
return pages;
}
if (index === -2) {
return pages[pages.length - 1];
}
if (index === -3) {
return pages[pages.length - 2];
}
return pages[index];
};
/**
* 验证当前页面是否为nvue页面
* @param {Object} page 当前页面对象
*/
export const isNvuePage = function (page) {
const cstr = page.constructor.name;
const pageType = {
s: true,
z: false,
};
return pageType[cstr];
};
/**
* @param {Object} page //当前顶级页面对象
* @param {Object} vim:? //是否获取 $vm 对象还是 $mp 对象
*/
export const getPageVmOrMp = function (page, vim = true) {
if (vim) {
return page.$vm;
}
if (page.$vm.$mp) {
return page.$vm.$mp;
}
if (isNvuePage(page)) { // nvue 页面
return {
page,
query: page.__displayReporter.query,
};
}
};
/**
* 获取 to 的配置参数
* @param {Object} rule 当前跳转的规则
*/
export const formatTo = function (finalRoute) {
const route = copyObject(finalRoute.route);
const { rule } = finalRoute;
route.query = rule.query || rule.params || {};
return route;
};
/**
* 通过一个未知的路径或者名称 在路由表中查找指定路由表 并返回
* @param {string} type //path 或者 name
* @param {Object} routes //当前对象的所有路由表
*/
export const pathOrNameToRoute = function (type, routes = Global.Router.CONFIG.routes) {
const routesKeys = Object.keys(routes);
for (let i = 0; i < routesKeys.length; i += 1) {
const key = routesKeys[i];
const item = routes[key];
if (item.path === `/${type}`) {
return mergeRoute(item); // 合并一下对象,主要是合并 query:{} 及 params:{}
}
if (item.path === type) {
return mergeRoute(item); // 合并一下对象,主要是合并 query:{} 及 params:{}
}
if (item.name == type) {
return mergeRoute(item); // 合并一下对象,主要是合并 query:{} 及 params:{}
}
}
err(`当前 '${type}' 在路由表中没有找到匹配的 name 或者 path`);
};
/**
* 统一格式话 路由传递的参数 看看是编码还是非编码 做相应的对策
*
* @param {Object} query 当前的路由参数
* @param {Boolean} getter 是从页面获取 route 对象下的参数 还是编码后传输
*/
export const getFormatQuery = function (query = {}) {
if (Global.Router.CONFIG.encodeURI) {
try {
query = JSON.parse(decodeURIComponent(query.query || encodeURIComponent('{}')));
} catch (e) {
query = JSON.parse(query.query);
}
}
return query;
};
/**
* 获取 from 的配置参数 from 页面永远都是站在当前页面忘其它地方走 所以都是最后一个页面
*
* @param {Object} routes //当前对象的所有路由表
*/
export const formatFrom = function (routes) {
const topPage = getPages(-2);
const { page, query } = getPageVmOrMp(topPage, false);
const route = pathOrNameToRoute(page.route, routes); // 获取到当前路由表下的 route
route.query = getFormatQuery(query); // 不管是编码传输还是非编码 最后都得在 to/from 中换成json对象
return route;
};
/**
*
* 把用户的跳转路由规则格式化成uni-app可用的路由跳转规则
*
* @param {Object} rule //当前用户跳转的路由规则
* @param {Object} routes //当前simple-router 下的路由表
*/
export const ruleToUniNavInfo = function (rule, routes) {
if (rule == null) {
return err('当前跳转规则为空,请检查跳转代码');
}
// eslint-disable-next-line
let [navType, route, query, animation] = ['path', null, {}, {}];
if (rule.constructor === String) { // 是字符串类型 那当前就是路径啦
route = pathOrNameToRoute(rule, routes); // 直接把 rule 当 path 传递 完事
} else if (rule.constructor === Object) { // 对象类型 可以是 path 或者 name
route = pathOrNameToRoute(rule.path || (navType = 'name', rule.name), routes); // 两则必有其一 报错自己处理
query = rule.query || rule.params || {};
animation = rule.animation || {};
} else {
return err('传的什么乱七八糟的类型?路由跳转规则只认字符串 \'path\' , 对象 \'path\' , 对象 \'name\' ');
}
animation = { ...Global.Router.CONFIG.APP.animation, ...route.animation || {}, ...animation }; // 合并多种方式声明的动画效果
route.animation = animation; // 这才是最终的页面切换效果
// 路径处理完后 开始格式化参数
const uniRoute = parseQuery(route.path, query); // uni-app 需要的跳转规则
return {
rule,
route,
uniRoute,
};
};
/**
* 获取当前页面下的 Route 信息
*
* @param {Object} pages 获取页面对象集合
* @param {Object} Vim 用户传递的当前页面对象
*/
export const APPGetPageRoute = function (pages, Vim) {
let [query, path] = [{}, ''];
const page = pages[pages.length - 1]; // 获取到当前页面
if (pages.length > 0) {
query = getFormatQuery(page.options, true);
path = page.route;
} else if (Vim != null) {
query = getFormatQuery(Vim.$mp.page.options, true);
path = page.route;
}
const route = pathOrNameToRoute(path);
route.query = query;
return route;
};
/**
* 获取当前页面下的 onBeforeBack 生命周期并执行
*
* @param {Object} args 当前返回页面时uni-app传递的参数
*/
export const getPageOnBeforeBack = function (args) {
return new Promise(async (resolve) => {
const currPage = getPages(-2); // 获取到当前页面
const { onBeforeBack } = currPage.$vm.$options;
if (onBeforeBack != null && onBeforeBack.constructor === Function) {
const isNext = await onBeforeBack.call(currPage.$vm, args);
if (isNext === true) {
return resolve(false);
}
}
return resolve(true);
});
};
/**
* 断言当前页面是否可返回上一级
* @param {Object} page 当前页面webview对象
*/
export const assertCanBack = function (page) {
const pageStyle = page.$getAppWebview().getStyle();
if (pageStyle.titleNView != null && pageStyle.titleNView.autoBackButton) { // 只有处理有带返回按钮的页面
return true;
}
// 两种情况 1.真的是顶级页面时 2.自定义头部
const { $page } = page;
if ($page && $page.meta.isQuit === false) { // 自定义头部 不是顶级页面
return true;
}
return false; // 不可返回 真的是顶级页面时 返回就直接退出app了
};
import { methods, Global } from '../helpers/config';
import { formatURLQuery } from '../helpers/util';
/**
* @param {Object} finalRoute 格式化后的路由跳转规则
* @param {Object} NAVTYPE 需要调用的跳转方法
*/
const appletsUniPushTo = function (finalRoute, NAVTYPE) {
return new Promise((resolve) => {
const query = formatURLQuery(`?${finalRoute.uniRoute.query}`);
const { url } = finalRoute.uniRoute;
uni[methods[NAVTYPE]]({
url: url + query,
complete: () => {
resolve(url);
Global.LockStatus = false; // 跳转完成解锁状态
},
});
});
};
export default appletsUniPushTo;
import { proxyLaunchHook } from './hooks';
/**
* 开始初始化app端路由配置
*
* @param {Object} Router 当前Router对象
*
* this 为当前 page 对象
*/
const appletsInit = function () {
proxyLaunchHook.call(this);
};
export default appletsInit;
import { Global, route as mergeRoute } from '../helpers/config';
import { copyObject, parseQuery } from '../helpers/util';
import { err } from '../helpers/warn';
import { baiduApple, touTiao } from '../helpers/compile';
/**
* 触发指定生命钩子
* @param {Array} funList //需要执行的方法列表
* @param {Object} args //触发生命钩子传递的参数
*/
export const callAppHook = function (funList, args) {
for (let i = 0; i < funList.length; i += 1) {
funList[i].call(this, args);
}
};
/**
* @param {Object} page //当前顶级页面对象
* @param {Object} vim:? //是否获取 $vm 对象还是 $mp 对象
*/
export const getPageVmOrMp = function (page, vim = true) {
if (vim) {
return page.$vm;
}
const { $mp } = page.$vm;
baiduApple(() => { // 百度小程序新增一个route属性
$mp.page.route = $mp.page.is;
});
touTiao(() => { // 头条小程序新增一个route属性
$mp.page.route = $mp.page.is;
});
return $mp;
};
/**
* 统一格式话 路由传递的参数 看看是编码还是非编码 做相应的对策
*
* @param {Object} query 当前的路由参数
* @param {Boolean} getter 是从页面获取 route 对象下的参数 还是编码后传输
*/
export const getFormatQuery = function (query = {}, getter = false) {
if (Global.Router.CONFIG.encodeURI) {
if (getter) {
try { // 除去微信小程序都不需要 decodeURIComponent
query = JSON.parse(decodeURIComponent(query.query) || '{}');
} catch (e) { // 其他小程序
query = JSON.parse(query.query || '{}');
}
} else {
try {
query = JSON.parse(decodeURIComponent(query.query || encodeURIComponent('{}')));
} catch (e) {
query = JSON.parse(query.query);
}
}
}
return query;
};
/**
* @param {Number} index //需要获取的页面下标 -2:表示获取最后一个即当前页面 -1:表示全部 -3:当前页面的前一个页面
* @param {Boolean} all //是否获取全部的页面
*/
export const getPages = function (index = -1, all) {
const pages = getCurrentPages(all);
if (index === -1) {
return pages;
}
if (index === -2) {
return pages[pages.length - 1];
}
if (index === -3) {
return pages[pages.length - 2];
}
return pages[index];
};
/**
* 通过一个未知的路径或者名称 在路由表中查找指定路由表 并返回
* @param {string} type //path 或者 name
* @param {Object} routes //当前对象的所有路由表
*/
export const pathOrNameToRoute = function (type, routes = Global.Router.CONFIG.routes) {
const routesKeys = Object.keys(routes);
for (let i = 0; i < routesKeys.length; i += 1) {
const key = routesKeys[i];
const item = routes[key];
if (item.path === `/${type}`) {
return mergeRoute(item); // 合并一下对象,主要是合并 query:{} 及 params:{}
}
if (item.path === type) {
return mergeRoute(item); // 合并一下对象,主要是合并 query:{} 及 params:{}
}
if (item.name == type) {
return mergeRoute(item); // 合并一下对象,主要是合并 query:{} 及 params:{}
}
}
err(`当前 '${type}' 在路由表中没有找到匹配的 name 或者 path`);
};
/**
* 获取 to 的配置参数
* @param {Object} rule 当前跳转的规则
*/
export const formatTo = function (finalRoute) {
const route = copyObject(finalRoute.route);
const { rule } = finalRoute;
route.query = rule.query || rule.params || {};
return route;
};
/**
* 获取 from 的配置参数 from 页面永远都是站在当前页面忘其它地方走 所以都是最后一个页面
*
* @param {Object} routes //当前对象的所有路由表
*/
export const formatFrom = function (routes) {
const topPage = getPages(-2);
const { page, query } = getPageVmOrMp(topPage, false);
const route = pathOrNameToRoute(page.route, routes); // 获取到当前路由表下的 route
route.query = getFormatQuery(query); // 不管是编码传输还是非编码 最后都得在 to/from 中换成json对象
return route;
};
/**
*
* 把用户的跳转路由规则格式化成uni-app可用的路由跳转规则
*
* @param {Object} rule //当前用户跳转的路由规则
* @param {Object} routes //当前simple-router 下的路由表
*/
export const ruleToUniNavInfo = function (rule, routes) {
if (rule == null) {
return err('当前跳转规则为空,请检查跳转代码');
}
// eslint-disable-next-line
let [navType, route, query] = ['path', null, {}];
if (rule.constructor === String) { // 是字符串类型 那当前就是路径啦
route = pathOrNameToRoute(rule, routes); // 直接把 rule 当 path 传递 完事
} else if (rule.constructor === Object) { // 对象类型 可以是 path 或者 name
route = pathOrNameToRoute(rule.path || (navType = 'name', rule.name), routes); // 两则必有其一 报错自己处理
query = rule.query || rule.params || {};
} else {
return err('传的什么乱七八糟的类型?路由跳转规则只认字符串 \'path\' , 对象 \'path\' , 对象 \'name\' ');
}
// 路径处理完后 开始格式化参数
const uniRoute = parseQuery(route.path, query); // uni-app 需要的跳转规则
return {
rule,
route,
uniRoute,
};
};
/**
* 获取当前页面下的 Route 信息
*
* @param {Object} pages 获取页面对象集合
* @param {Object} Vim 用户传递的当前页面对象
*/
export const AppletsPageRoute = function (pages, Vim) {
let [query, path] = [{}, ''];
const page = pages[pages.length - 1]; // 获取到当前页面
if (pages.length > 0) {
const uniQuery = getPageVmOrMp(page, false).query;
query = getFormatQuery(uniQuery, true);
path = page.route;
} else if (Vim != null) {
query = getFormatQuery(Vim.$mp.page.options, true);
path = page.route;
}
const route = pathOrNameToRoute(path);
route.query = query;
return route;
};
const render = function (node) {
if (typeof node == 'string') { // 是一个文本节点
return document.createTextNode(node);
}
if (node instanceof HTMLElement) {
return node;
}
// eslint-disable-next-line
return createElement(node);
};
/**
* 根据标签及属性创建一个dom
*/
const createElement = function ({
tag,
attrs,
children,
} = {}) {
const $el = document.createElement(tag);
// eslint-disable-next-line
for (const [k, v] of Object.entries(attrs)) {
$el.setAttribute(k, v);
}
// eslint-disable-next-line
for (const item of children) {
$el.appendChild(render(item));
}
return $el;
};
const html = createElement({
tag: 'div',
attrs: {
id: 'router-loadding',
},
children: [
createElement({
tag: 'div',
attrs: {
class: 'loadding',
},
children: [],
}),
],
});
/* eslint-disable */
const style = createElement({
tag: 'style',
attrs: {
id: 'HHYANG_style',
},
children: [
`
body{padding:0;margin:0}#router-loadding{position:fixed;width:100%;height:3px;transition:all .05s;top:0;z-index:9999999999999999;}#router-loadding .loadding{position:fixed;top:0;height:3px;background-color:#47b14b;width:0;box-shadow:0 0 15px #4CAF50;transition:all .8s;border-top-right-radius:3px;border-bottom-right-radius:3px}
`,
],
});
const script = createElement({
tag: 'script',
attrs: {
id: 'HHYANG_script',
},
children: [
`
var HHYANG_El=document.querySelector("#router-loadding .loadding"),HHYANG_Pel=document.querySelector("#router-loadding"),w=0,stop=null,WH=window.innerWidth,loop=function(){w=w>=WH-35?w+parseInt(5*Math.random()):w+parseInt(35*Math.random());HHYANG_El.style.cssText="width:"+w+"px";w>=WH&&clearInterval(stop)};window.startLodding=function(a){a=void 0===a?500:a;HHYANG_Pel.style.cssText="display: block;";HHYANG_El.style.cssText="transition: all 0.8s;";w=0;clearInterval(stop);stop=setInterval(function(){loop()},a)};window.stopLodding=function(a){a=void 0===a?200:a;clearInterval(stop);HHYANG_El.style.cssText="width:"+WH+"px;transition: all "+a/1E3+"s;";HHYANG_Pel.style.cssText="opacity: 0;transition: all "+a/1E3+"s;";setTimeout(function(){HHYANG_Pel.style.cssText="display: none;";HHYANG_El.style.cssText="width:0px";w=0},a)};
`,
],
});
export const DOM = {
style,
html,
script,
};
/* eslint-enable */
<template>
<view @click="gotoPage()"><slot></slot></view>
</template>
<script>
const navType = {
push: 'push',
replace: 'replace',
replaceAll: 'replaceAll',
pushTab: 'pushTab'
};
export default {
props: {
to: {
type: [String, Object],
},
stopNavto: {
type: Boolean,
default: false
},
navType: {
type: String,
default: 'push'
},
level: {
type: Number,
default: 1
},
append: {
type: Boolean,
default: false
}
},
methods: {
formatNav(text) {
if (text != null && text.constructor === String) {
text = text.replace(/\'/g, '');
text = text.replace(/(\w+)(?=:)/g, function(val) {
return `"${val}"`;
});
text = text.replace(/:\s*([^,{}\s"]+)/g, function(val) {
const arr = val.split(':');
return `:"${arr[1].trim()}"`;
});
try {
text = JSON.parse(text);
} catch (e) {}
}
if (this.append) {
let pathArr = this.$Route.path.split('/');
pathArr.splice(pathArr.length - this.level, this.level);
pathArr = pathArr.join('/');
if (text.constructor === Object) {
if (text.path) {
text.path = pathArr + text.path;
}
} else {
text = pathArr + text;
}
}
return text;
},
gotoPage() {
if (this.stopNavto) {
return true;
}
const type = navType[this.navType];
if (type == null) {
return console.error(` "navType" unknown type \n\n value:${Object.values(navType).join('、')}`);
}
const navInfo = this.formatNav(this.to);
this.$Router[type](navInfo);
}
}
};
</script>
<style></style>
export const H5 = function (fn) {
// #ifdef H5
fn();
// #endif
};
export const APP = function (fn) {
// #ifdef APP-PLUS
fn();
// #endif
};
export const applets = function (fn) {
// #ifdef MP
fn();
// #endif
};
export const notH5 = function (fn) {
// #ifndef H5
fn();
// #endif
};
export const baiduApple = function (fn) {
// #ifdef MP-BAIDU
fn();
// #endif
};
export const touTiao = function (fn) {
// #ifdef MP-TOUTIAO
fn();
// #endif
};
export const mp = function (fn) {
// #ifdef MP
fn();
// #endif
};
export const baseConfig = {
h5: {
rewriteFun: true, // 是否对uni-app reLaunch/navigateBack 两个方法重写 处理uni刷新直接返回到首页和触发路由守卫
paramsToQuery: false, // h5端上通过params传参时规则是vue-router 刷新会丢失 开启此开关将变成?连接的方式
loading: true, // 是否显示加载动画
hinderTab: false, // 是否拦截uni-app自带底部菜单 TODO
vueRouterDev: false, // 完全使用采用vue-router的开发模式
useUniConfig: true, // 是否采用在pages.json下的所有页面配置信息,false时需开发者自行设置页面
keepUniIntercept: false, // 保留uni-app使用vue-router的拦截器
vueNext: false, // 在next管道函数中是否获取vueRouter next的原本参数
replaceStyle: false, // 是否对resetStyle函数中返回的style节点进行全部替换,否则为追加
resetStyle: () => JSON.parse('{}'), // 自定义加载样式函数 可返回一个包涵 html、style、script 的对象来重置Router内置的加载动画
mode: 'hash',
base: '/',
linkActiveClass: 'router-link-active',
linkExactActiveClass: 'router-link-exact-active',
scrollBehavior: (to, from, savedPostion) => savedPostion,
fallback: true,
},
APP: {
holdTabbar: true, // 是否开启底部菜单拦截
loddingPageStyle: () => JSON.parse('{"backgroundColor":"#FFF"}'), // 当前等待页面的样式 必须返回一个json
loddingPageHook: (view) => { plus.navigator.closeSplashscreen(); view.show(); }, // 刚刚打开页面处于等待状态,会触发此事件
animation: { animationType: 'pop-in', animationDuration: 300 }, // 页面切换动画
switchPageOutTime: 1000, // 最高能忍耐的页面切换时间 达到此时间 不管切换有没有完成都会显示页面出来 这对启动页帮助很大
},
debugger: false, // 是否处于开发阶段 设置为true则打印日志
encodeURI: true, // 是否对url传递的参数进行编码
routerBeforeEach: () => {}, // router 前置路由函数 每次触发跳转前先会触发此函数
routerAfterEach: () => {}, // router 后置路由函数 每次触发跳转后会触发此函数
routes: [],
};
export const methods = {
push: 'navigateTo',
replace: 'redirectTo',
replaceAll: 'reLaunch',
pushTab: 'switchTab',
back: 'navigateBack',
};
export const H5FnTypeToggle = {
push: 'push',
replace: 'replace',
replaceAll: 'replace',
pushTab: 'replace',
};
export const lifeCycle = {
beforeHooks: [],
afterHooks: [],
routerHooks: [],
routerbeforeHooks: [], // 内部跳转前生命周期
routerAfterHooks: [], // 内部跳转后生命周期
};
export const Global = { // 缓存一些必要的对象,作为全局可以访问的参数
$parseQuery: null, // url query 帮助类实例
Router: {},
vueRouter: {},
addedRoutes: [], // 用于缓存用户动态添加的路由
RouterReadyPromise: () => {},
H5RouterReady: null, // 当前router是否就绪
backLayerC: 1, // 返回api调用时开发者传递的 delta
LockStatus: false, // 当前是否正在进行跳转 正在跳转调用api是不给跳转的
};
export const uniAppHook = {
indexVue: {}, // 首页 组件对象
toutiaoIndexThis: {}, // 头条小程序Index this对象
appVue: {}, // 同getApp()获取到的对象一毛一样的 其实就是app.vue组件
onLaunch: { fun: [], args: {}, isHijack: false }, // 这两个是app.vue
onShow: { fun: [], args: {}, isHijack: false },
variationFuns: ['onReady', 'onUnload'], // 一些uni-app的变异方法 需要处理下
waitHooks: {}, // 首页等待中的生命钩子 一些需要等待的Hooks,就是在页面没有进来之前一些提前触发的生命钩子 主要是用户已经声明好的
indexCallHooks: ['onLoad', 'onReady', 'created', 'onShow'], // 在首页首次启动时需要触发的生命周期
needHooks: ['onLoad', 'onReady', 'onShow', 'created', 'onHide', 'onUnload', 'onResize'], // 首页需要拦截的生命钩子
pageReady: false,
onLaunched: false, // 否触发onLaunch事件
};
export const appletsConfig = { // 小程序端的一些路由所需配置
onLaunchEd: false, // 当前小程序端是否触发onLaunch事件
};
export const route = function (object = {}) {
return {
...object,
params: {},
query: {},
};
};
import { uniAppHook } from './config';
import H5init from '../vueRouter/init';
import { appInit, removeBackPressEvent, pageIsHeadBack } from '../appRouter/init';
import appletsInit from '../appletsRouter/init';
import { appPlatform } from './util';
import { proxyIndexHook } from '../appRouter/hooks';
import { appletsProxyIndexHook } from '../appletsRouter/hooks';
/**
* 获取一些需要在各个平台混入的事件
* @param {Object} Router 当前原始路由对象
*/
const getMixins = function (Router) {
return {
H5: {
beforeCreate() {
if (this.$options.router) {
H5init(Router.$root, this.$options.router, this);
}
},
},
APP: {
onLaunch() {
uniAppHook.onLaunched = true; // 标志已经触发了 onLaunch 事件
appInit.call(this, Router.$root);
},
onLoad() {
// 第一个页面 拦截所有生命周期
if (uniAppHook.onLaunched && !uniAppHook.pageReady) {
uniAppHook.onLaunched = false;
proxyIndexHook.call(this, Router.$root);
}
removeBackPressEvent(this.$mp.page, this.$options); // 移除页面的onBackPress事件
},
onBackPress(...args) {
return pageIsHeadBack.call(Router.$root, this.$mp.page, this.$options, args);
},
},
APPLETS: {
onLaunch() {
uniAppHook.onLaunched = true; // 标志已经触发了 onLaunch 事件
appletsInit.call(this, Router.$root);
},
onLoad() {
if (uniAppHook.onLaunched && !uniAppHook.pageReady) { // 必须是第一个页面
uniAppHook.onLaunched = false;
appletsProxyIndexHook.call(this, Router.$root);
}
},
},
};
};
const initMixins = function (Vue, Router) {
Vue.mixin({
...getMixins(Router)[appPlatform(true)],
});
};
export default initMixins;
import { appPlatform } from './util';
import { methods, H5FnTypeToggle, Global } from './config';
import { transitionTo } from '../appRouter/hooks';
import { appletsTransitionTo, backCallHook } from '../appletsRouter/hooks';
import uniPushTo from '../appRouter/uniNav';
import appletsUniPushTo from '../appletsRouter/appletsNav';
import { err, warn } from './warn';
import H5PushTo from '../vueRouter/routerNav';
import * as compile from './compile';
/**
* 返回api 触发的公共函数
* @param {Object/String} rule 当前跳转规则
* @param {String} fnType 跳转页面的类型方法
*
* this 为当前 Router 实例
*/
const isBcakNav = function ({
backLayer,
delta,
H5PATCH,
}) {
compile.H5(() => {
H5PATCH.on('historyBack', {
backLayer,
delta,
});
});
compile.APP(() => {
Global.backLayerC = backLayer; // 告诉路由需要返回几层
uni.navigateBack({
delta: backLayer,
complete: () => {
Global.LockStatus = false; // 跳转完成解锁状态
},
});
});
compile.mp(() => {
backCallHook.call(this, backLayer, () => {
uni.navigateBack({
delta: backLayer,
});
});
});
};
/**
* 非 返回api 触发的公共函数
* @param {Object/String} rule 当前跳转规则
* @param {String} fnType 跳转页面的类型方法
*
* this 为当前 Router 实例
*/
const notBackNav = function (rule, fnType) {
if (rule == null) {
return err('跳转规则为空,不允许这样操作');
}
if (rule.constructor === String) { // 单独 path 的情况 允许?拼接参数
const ruleArray = rule.split('?');
if (ruleArray.length > 1) {
rule = {
path: ruleArray[0],
query: Global.$parseQuery.parse(ruleArray[1]),
};
}
}
switch (appPlatform(true)) {
case 'H5':
return H5PushTo.call(this, H5FnTypeToggle[fnType], rule, methods[fnType]);
case 'APP':
Global.LockStatus = true; // 设置为锁住状态
return transitionTo.call(this, rule, fnType, uniPushTo);
case 'APPLETS':
Global.LockStatus = true; // 设置为锁住状态
return appletsTransitionTo.call(this, rule, fnType, appletsUniPushTo);
default:
err('糟糕!!!还有其他的执行环境???没听说过啊。一脸懵逼???加QQ群问问:769241495');
break;
}
};
/**
* 处理正在跳转的公共api
* @param {Object/String} rule 当前跳转规则
* @param {String} fnType 跳转页面的类型方法
* @param {Boolean} isBack 是否通过 back() api 调用的 默认为false
* @param {Boolean} enforce 是否强制越过跳转加锁检查 默认false 目前只有back() api 传递了
*
* this 为当前 Router 实例
*/
const navjump = function (rule, fnType, isBack = false, enforce = false) {
if (Global.LockStatus && !enforce) { // 正在跳转的状态下 给出提示正在跳转
return warn('当前页面正在处于跳转状态,请稍后再进行跳转....');
}
if (isBack) { // 是返回api触发的
return isBcakNav.call(this, rule, fnType);
}
return notBackNav.call(this, rule, fnType);
};
export default navjump;
import { Global } from './config';
import { warn, err } from './warn';
const nodeURL = require('query-string');
class ParseQuery {
get queryName() {
return nodeURL;
}
/**
* 判断当前这个对象是否为深度对象
* @param {Object} obj
*/
isDepthObject(obj) {
const str = JSON.stringify(obj);
return str.match(/}/g).length > 1;
}
/**
* 从URL中提取查询字符串
* @param {String} url
*/
extract(url) {
return nodeURL.extract(url);
}
/**
* 把一个 key=value&key1=value 的字符串转成对象
* @param {string} strQuery key=value&key1=value 类型的字符串
*/
parse(strQuery) {
return nodeURL.parse(strQuery);
}
/**
* 把一个对象转成 key=value&key1=value 类型的字符串
* @param {Object} ObjQuery 符合js标注的对象
* @param {Boolean} intact 是否在转成的字符串前添加?号
*/
stringify(ObjQuery, intact = true) {
const strQuery = nodeURL.stringify(ObjQuery);
if (intact) {
return `?${strQuery}`;
}
return strQuery;
}
/**
* 把一个对象或者 key=value&key1=value 类型的数据加密成 query=encodeURIComponent(value)
* @param {Object|String} query 符合js标注的对象 或者 key=value&key1=value 字符串
* @param {Boolean} intact 是否在转成的字符串前添加?号
*/
encode(query, intact = true) {
let [strQuery, formatQuery] = ['', ''];
if (query == null) {
warn('加密参数没有传递,你知道?', true);
return '';
}
if (query.constructor === String) { // 字符串 尝试 转成 对象
strQuery = JSON.stringify(this.parse(query));
} else if (query.constructor === Object) { // 直接转成字符串对象即可
if (Object.keys(query).length === 0) {
warn('当前参数不满足加密规范!');
return '';
}
strQuery = JSON.stringify(query);
}
if (intact) {
formatQuery = '?';
}
formatQuery += `query=${encodeURIComponent(strQuery)}`;
return formatQuery;
}
/**
* 把一个已经加密好的字符串 query=encodeURIComponent(value) 解密成 对象
* @param {string} strQuery 已经加密好的字符串 query=encodeURIComponent(value)
*/
decode(strQuery) {
if (strQuery == null) {
warn('解密参数没有传递,你知道?', true);
return {};
}
let jsonQuery = strQuery;
if (strQuery.constructor === Object) { // 如果是对象 看能不能满足要求
jsonQuery = strQuery.query;
if (jsonQuery == null) {
warn('当前解密参数不满足编码规则');
return {};
}
jsonQuery = `query=${jsonQuery}`;
}
let decode = {};
// query 长这个样 query=encodeURIComponent(value)
const decodeStr = decodeURIComponent(jsonQuery);
const { query } = this.parse(decodeStr); // 转成 json 获取到正真的json字符串
if (query == null) {
warn('当前解密参数不满足编码规则');
} else {
try {
decode = JSON.parse(query);
} catch (error) {
warn('当前解密参数不满足编码规则');
}
}
return decode;
}
queryGet(query) {
const { encodeURI } = Global.Router.CONFIG; // 获取到路由配置
let [decode, historyObj, strQuery] = [query, query, ''];
switch (encodeURI) {
case true: { // 加密模式
decode = this.decode(query);
strQuery = this.encode(decode);
historyObj = {
query: encodeURIComponent(JSON.stringify(decode)),
};
break;
}
case false: { // 不加密模式
strQuery = this.stringify(query);
break;
}
default: {
err('未知参数模式,请检查 \'encodeURI\'', true);
}
}
return { strQuery, historyObj, decode };
}
/**
* 对需要传递的参数进行加密解密
* @param {Object|String} query get为false 必须为 Object 类型
* @param {String} get 是取值 还是通过api传值
*/
transfer(query = {}) {
const { encodeURI } = Global.Router.CONFIG; // 获取到路由配置
switch (encodeURI) {
case true: {
// 加密模式
return this.encode(query, false);
}
case false: {
// 不加密模式
return this.stringify(query);
}
default: {
err('未知参数模式,请检查 \'encodeURI\' ', true);
}
}
}
}
export default ParseQuery;
import { route, baseConfig, Global } from './config';
import { builtIn } from '../vueRouter/base';
import { err, log, warn } from './warn';
/**
* 当前是不是H5运行环境
*/
export const isH5 = function () {
return typeof window !== 'undefined' && typeof document !== 'undefined';
};
/**
* 判断当前变量是否为Object
* @param {Object} strObj
*/
export const isObject = function (strObj) {
return strObj.toString() === '[object Object]' && strObj.constructor === Object;
};
/**
* 获取当前运行平台
* @param {Boolean} applets 默认false true时所有小程序平台统一返回 APPLETS
*/
export const appPlatform = function (applets = false) {
let platform = '';
// #ifdef APP-PLUS-NVUE
platform = 'APPNVUE';
// #endif
// #ifdef APP-PLUS
platform = 'APP';
// #endif
// #ifdef H5
platform = 'H5';
// #endif
// #ifdef MP-ALIPAY
platform = 'ALIPAY';
// #endif
// #ifdef MP-BAIDU
platform = 'BAIDU';
// #endif
// #ifdef MP-QQ
platform = 'QQ';
// #endif
// #ifdef MP-WEIXIN
platform = 'WEIXIN';
// #endif
// #ifdef MP-TOUTIAO
platform = 'TOUTIAO';
// #endif
if (applets) {
// #ifdef MP
platform = 'APPLETS';
// #endif
}
return platform;
};
/**
* 定义一个空方法 如果最后一个参数为true则打印所有参数
* @param {...any} args
*/
export const noop = function (...args) {
if (args[args.length - 1] === true) {
log(args);
}
};
/**
* 格式化基础配置信息 通过new Router传递过来的参数
*/
export const formatConfig = function (userConfig) {
if (!userConfig.routes || userConfig.routes.constructor !== Array) {
return err(`路由参数 'routes' 必须传递 \r\n\r\n${JSON.stringify(userConfig)}`);
}
if (userConfig.h5 != null && userConfig.h5.constructor !== Object) {
return err(`h5参数传递错误,应该是一个 'Object' 类型 示例:\r\n\r\n${JSON.stringify(baseConfig.h5)}`);
}
const config = Object.create(null);
const baseConfigKeys = Object.keys(baseConfig);
for (let i = 0; i < baseConfigKeys.length; i += 1) {
const key = baseConfigKeys[i];
if (userConfig[key] != null) {
if (userConfig[key].constructor === Object) {
config[key] = {
...baseConfig[key],
...userConfig[key],
};
} else if (key == 'routes') { // 需要加入已知的白名单
config[key] = [...baseConfig[key], ...userConfig[key], ...builtIn];
} else {
config[key] = userConfig[key];
}
} else {
config[key] = baseConfig[key];
}
}
return config;
};
export const filter = function (str) {
str += '';
str = str.replace(/%/g, '%25');
str = str.replace(/\+/g, '%2B');
str = str.replace(/ /g, '%20');
str = str.replace(/\//g, '%2F');
str = str.replace(/\?/g, '%3F');
str = str.replace(/&/g, '%26');
str = str.replace(/=/g, '%3D');
str = str.replace(/#/g, '%23');
return str;
};
/**
* 使用encodeURI:true的情况 需要进行编码后再传递,解码等等 可以传递深度对象并会在路径后面加入一个query=
*
* @param {String} routerName //路径名称
* @param {JSON} query //需要格式化参数
* @param {Boolean} Encode //是获取还是编码后传递
*/
export const parseQueryN = function (routerName, query, Encode) {
if (Encode) {
return {
url: routerName,
query: JSON.parse(decodeURIComponent(query.replace(/^query=/, ''))),
};
}
return {
url: routerName,
query: `query=${encodeURIComponent(JSON.stringify(query))}`,
};
};
/**
* 使用encodeURI:false的情况 直接格式化为普通的queryURl参数形式传递即可 扁平深度对象
*
* @param {String} routerName //路径名称
* @param {JSON} query //需要格式化参数
* @param {Boolean} Encode //是获取还是编码后传递
*/
export const parseQueryD = function (routerName, query, Encode) {
if (Encode) {
const obj = {};
const reg = /([^=&\s]+)[=\s]*([^&\s]*)/g;
while (reg.exec(query)) {
obj[RegExp.$1] = RegExp.$2;
}
return {
url: routerName,
query: obj,
};
}
const encodeArr = [];
const queryKeys = Object.keys(query);
for (let i = 0; i < queryKeys.length; i += 1) {
const attr = queryKeys[i];
let encodeStr = '';
if (query[attr].constructor == Object) {
encodeStr = parseQueryD(routerName, query[attr], Encode).query;
encodeArr.push(encodeStr);
} else {
encodeStr = filter(query[attr]);
encodeArr.push(`${attr}=${encodeStr}`);
}
}
return {
url: routerName,
query: encodeArr.join('&'),
};
};
/**
* @param {String} routerName //路径名称
* @param {JSON} query //需要格式化参数
* @param {Boolean} Encode //是获取还是编码后传递
*/
export const parseQuery = function (routerName, query, Encode = false) {
if (Global.Router.CONFIG.encodeURI) {
return parseQueryN(routerName, query, Encode);
}
return parseQueryD(routerName, query, Encode);
};
export const exactRule = function (cloneRule, routes, ruleKey, getRule = false) {
const params = {};
let i = 0;
// eslint-disable-next-line
while (true) {
const item = routes[i];
if (item == null) {
if (!getRule) {
err(`路由表中未查找到 '${ruleKey}' 为 '${cloneRule[ruleKey]}'`);
}
return {
path: '',
name: '',
};
}
if (item[ruleKey] != null && item[ruleKey] === cloneRule[ruleKey]) {
if (!getRule) {
params.url = item.path;
params.rule = item;
if (isH5()) { // 如果是h5 则使用优先使用自定义路径名称
params.url = item.aliasPath || item.path;
}
return params;
}
return item;
}
i += 1;
}
};
export const resolveRule = function (router, rule, query = {}, ruleKey = 'path') {
const ruleInfo = route(
exactRule({
...rule,
},
router.CONFIG.routes,
ruleKey,
router),
);
return {
...ruleInfo,
query,
};
};
/**
* 把一些不必要的参数进行格式化掉,完成url的美观
* @param {String} URLQuery URL中传递的参数
*/
export const formatURLQuery = function (URLQuery) {
switch (URLQuery.trim()) {
case 'query=%7B%7D':
case '%7B%7D':
case '?query=%7B%7D':
case '?':
case '?[object Object]':
case '?query={}':
URLQuery = '';
break;
default:
warn('url已经很完美啦,不需要格式化!');
break;
}
return URLQuery;
};
/**
* 拷贝对象
* @param {Object} object
*/
export const copyObject = function (object) {
return JSON.parse(JSON.stringify(object));
};
import { Global } from './config';
const isLog = function (type, errText, enforce) {
if (!enforce) {
const dev = Global.Router.CONFIG.debugger;
const isObject = dev.toString() === '[object Object]';
if (dev === false) {
return false;
} if (dev === false) {
return false;
} if (isObject) {
if (dev[type] === false) {
return false;
}
}
}
/* eslint no-console:"off" */
console[type](errText);
};
export const err = function (errInfo, enforce = false) {
isLog('error', errInfo, enforce);
};
export const warn = function (errInfo, enforce = false) {
isLog('warn', errInfo, enforce);
};
export const log = function (errInfo, enforce = false) {
isLog('log', errInfo, enforce);
};
export const warnLock = function (errInfo) {
console.warn(errInfo);
};
import { isH5, formatConfig, appPlatform } from './helpers/util';
import navjump from './helpers/navJump';
import { H5GetPageRoute } from './vueRouter/util';
import { APPGetPageRoute } from './appRouter/util';
import { AppletsPageRoute } from './appletsRouter/util';
import { lifeCycle, Global } from './helpers/config';
import { warn, err } from './helpers/warn';
import { registerRouterHooks, registerHook } from './lifeCycle/hooks';
import { vueMount } from './vueRouter/base';
import appletsMount from './patch/applets-patch';
import appMount from './patch/app-patch';
import initMixins from './helpers/mixins';
import ParseQuery from './helpers/urlQuery';
// #ifdef H5
import H5 from './patch/h5-patch';
// #endif
let H5PATCH = null;
// #ifdef H5
H5PATCH = new H5(isH5());
// #endif
const parseQuery = new ParseQuery();
Global.H5RouterReady = new Promise((resolve) => Global.RouterReadyPromise = resolve);
class Router {
constructor(arg) {
Router.$root = this;
Global.Router = this; // 全局缓存一个对象,不必使用时都传递
Global.$parseQuery = parseQuery;
this.CONFIG = formatConfig(arg);
this.lifeCycle = lifeCycle;
registerRouterHooks.call(this); // 注册全局Router生命钩子
if (appPlatform() === 'H5') {
H5PATCH.setLoadingStatus(this.CONFIG.h5);
}
}
get $Route() {
return this.getPageRoute();
}
/**
* 获取 url 参数帮助类实例
*/
get $parseQuery() {
return Global.$parseQuery;
}
/**
* 获取当前是否处于正在跳转的状态
* H5 状态下始终为false
*/
get $lockStatus() {
return Global.LockStatus;
}
/**
* 动态设置拦截状态
*/
set $lockStatus(status) {
warn('你确定要这么做?你知道后果?', true);
Global.LockStatus = status;
}
/** 动态的导航到一个新 URL 保留浏览历史
* navigateTo
* @param {Object} rule
*/
push(rule) {
navjump.call(this, rule, 'push');
}
/** 动态的导航到一个新 URL 关闭当前页面,跳转到的某个页面。
* redirectTo
* @param {Object} rule
*/
replace(rule) {
navjump.call(this, rule, 'replace');
}
/** 动态的导航到一个新 URL 关闭所有页面,打开到应用内的某个页面
* reLaunch
* @param {Object} rule
*/
replaceAll(rule) {
navjump.call(this, rule, 'replaceAll');
}
/** 动态的导航到一个新 url 关闭所有页面,打开到应用内的某个tab
* @param {Object} rule
*/
pushTab(rule) {
navjump.call(this, rule, 'pushTab');
}
/**
* 返回到指定层级页面上
* @param {Number} backLayer 需要返回的页面层级 默认 1
* @param {Object} delta 暂时无用
* @param {enforce} 是否强制越过跳转加锁检查 默认 false
*/
back(backLayer = 1, delta, enforce = false) {
if (backLayer.constructor != Number) {
return err(
`返回层级参数必须是一个Number类型且必须大于1:${backLayer}`,
);
}
navjump.call(this, {
backLayer, delta, H5PATCH,
}, 'back', true, enforce);
}
/**
* 获取当前页面下的 Route 信息
*
* @param {Object} Vim 当前开发者可以传递一个 vue 组件对象 来获取当前下的 Route 信息
*/
getPageRoute(Vim) {
const pages = getCurrentPages();
switch (appPlatform(true)) {
case 'H5':
return H5GetPageRoute.call(this, pages, Vim);
case 'APP':
return APPGetPageRoute(pages, Vim);
case 'APPLETS':
return AppletsPageRoute(pages, Vim);
default:
break;
}
}
beforeEach(fn) {
return registerHook(this.lifeCycle.beforeHooks, fn);
}
afterEach(fn) {
return registerHook(this.lifeCycle.afterHooks, fn);
}
}
Router.install = function (Vue) {
initMixins(Vue, Router);
Object.defineProperty(Vue.prototype, '$Router', {
get() {
return Router.$root;
},
});
Object.defineProperty(Vue.prototype, '$Route', {
get() {
return Router.$root.getPageRoute(this);
},
});
};
export default Router;
/**
*
* @param {VueComponent } Vim vue实例对象
* @param {dom} el dom节点选择器
*/
export const RouterMount = function (Vim, el) {
switch (appPlatform(true)) {
case 'APP':
appMount(Vim, el);
break;
case 'APPLETS':
appletsMount(Vim, el);
break;
case 'H5':
vueMount.push({ Vim, el });
break;
default:
warn('糟糕!!!还有其他的执行环境???没听说过啊。一脸懵逼???加QQ群问问:769241495');
break;
}
};
import { appPlatform, isH5 } from '../helpers/util';
// #ifdef H5
import H5 from '../patch/h5-patch';
const H5PATCH = new H5(isH5());
// #endif
export const registerHook = function (list, fn) {
list.push(fn);
return () => {
const i = list.indexOf(fn);
if (i > -1) list.splice(i, 1);
};
};
/**
* 注册全局Router生命钩子
*/
export const registerRouterHooks = function () {
registerHook(this.lifeCycle.routerbeforeHooks, function () {
return new Promise(async (resolve) => {
this.CONFIG.routerBeforeEach(); // 触发暴露给开发者的生命钩子
if (appPlatform(true) === 'H5') {
H5PATCH.on('toogle', 'startLodding');
}
return resolve(true);
});
});
registerHook(this.lifeCycle.routerAfterHooks, function (res = {}) {
if (res.H5Intercept !== true) {
this.CONFIG.routerAfterEach(); // 触发暴露给开发者的生命钩子
}
if (appPlatform(true) === 'H5') {
H5PATCH.on('toogle', 'stopLodding');
}
return true;
});
};
{
"name": "uni-simple-router",
"version": "1.5.5",
"description": "> 一个更为简洁的[Vue-router](https://router.vuejs.org/zh/),专为 [uni-app](https://uniapp.dcloud.io/) 量身打造",
"main": "index.js",
"directories": {
"example": "examples"
},
"scripts": {
"postinstall": "node -e \"console.log('\\x1B[32m \\x1B[1m','\\n 欢迎下载 uni-simple-router ↓↓↓↓ \\n\\n 注意事项:\\n 1: 编译为app端如果开启V3,请关闭fast启动模式 \\n 2: 多看文档,特别是‘快速上手’栏目。文档地址:http://hhyang.cn/ \\n 3: 不要再问路由表是否可以不配置两遍。问就是文档有!\\n 4: 有啥问题解决不了的加群:769241495 \\n 5: 任何时候你都可以在github上提出你的想法及问题,相信我很快会得到回应 \\n\\n showTime:\\n 1:开源不易,需要鼓励。去给 uni-simple-router 项目 点个 star 吧 \\n')\""
},
"dependencies": {
"query-string": "^6.12.1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SilurianYang/uni-simple-router.git"
},
"keywords": [
"router",
"uni-app-router",
"interceptor",
"uni-app",
"uniapp"
],
"author": "hhyang",
"license": "MIT",
"bugs": {
"url": "https://github.com/SilurianYang/uni-simple-router/issues"
},
"homepage": "https://github.com/SilurianYang/uni-simple-router#readme",
"types": "./types/index.d.ts"
}
\ No newline at end of file \ No newline at end of file
/**
* 截止 1.3.5 版本 不做任何操作
* @param {element} el dom节点
*/
const appMount = function (Vim) {
Vim.$mount();
};
export default appMount;
/**
* 截止 1.3.5 版本 不做任何操作
* @param {element} el dom节点
*/
const appletsMount = function (Vim) {
Vim.$mount();
};
export default appletsMount;
// #ifdef H5
import { DOM } from '../component/h5-dom';
import init from '../vueRouter/init';
// #endif
import { warn } from '../helpers/warn';
class Patch {
constructor(H5) {
this.H5 = H5;
this.isLoading = true;
this.loadingCount = 0; // 在APP.vue中进行跳转时,DOMContentLoaded过慢。使用索引来判断
}
on(fun, args, callback) {
if (this.H5) {
return this[fun](args);
}
if (callback) {
callback();
}
}
/**
*把vueRouter的生命周期代理过来
* @param {Object} Router
* @param {Object} vueRouter
* @param {VueComponent} vueVim
*/
// eslint-disable-next-line
registerHook(Router, vueRouter, vueVim) {
init(Router, vueRouter, vueVim);
}
/**
* H5 专属 history.back API
* @param {Number} backLayer 需要返回的层级必须是正整数
* 2020年1月14日14:39:38 修复 https://github.com/SilurianYang/uni-simple-router/issues/73
*/
// eslint-disable-next-line
historyBack({ backLayer, delta = { from: 'navigateBack' } } = {}) {
const pages = getCurrentPages();
const page = pages[pages.length - 1];
const { onBackPress } = page.$options;
if (onBackPress != null && onBackPress.constructor === Array) {
const callFun = onBackPress[onBackPress.length - 1];
const isNext = callFun.call(page, delta);
if (isNext) {
return true;
}
}
// eslint-disable-next-line
history.go(-backLayer);
}
/**
* 把加载动画添加到dom下面,为什么一定要先添加,后移除。保证动画的连续性
*/
appendHTML({
style,
html,
script,
}) {
window.addEventListener('DOMContentLoaded', () => {
const body = document.querySelector('body');
body.appendChild(style);
body.appendChild(html);
body.appendChild(script);
this.toogle('startLodding', true);
});
}
/**
* 页面是否加载完毕触发对应事件
*/
toogle(toogle, DOMContentLoaded = false) {
if (DOMContentLoaded && this.loadingCount !== 0) {
this.loadingCount += 1;
return false;
}
try {
this.loadingCount += 1;
if (this.isLoading) {
window[toogle]();
}
} catch (error) {
warn('你使用了 addRoutes API 提前进行了生命周期 并触发了startLodding');
}
}
async setLoadingStatus({
loading,
replaceStyle,
resetStyle,
}) {
this.isLoading = loading;
if (loading) { // 确认需要加载样式 开始插入节点
const userStyle = resetStyle();
const userStyleKeys = Object.keys(userStyle);
for (let i = 0; i < userStyleKeys.length; i += 1) {
const key = userStyleKeys[i];
let html = userStyle[key];
if (key === 'style' && !replaceStyle) { // 开发者设置为追加style
html = DOM[key].innerHTML + html;
}
DOM[key].innerHTML = html;
}
this.appendHTML(DOM);
}
}
}
export default Patch;
import {Component,PluginFunction,Location,Route,Animation,H5,APP,RouteConfig,RouterOptions} from './options'
/**
* 路由挂载点
* @param {VueComponent } Vim vue实例对象
* @param {dom} el dom节点选择器
*/
declare const RouterMount: (Vim: any, el: string | Element) => void;
declare class Router {
constructor(options:RouterOptions)
/**
* 当前的 Route
*/
get $Route():Route;
/**
* 获取 url 参数帮助类实例
*/
get $parseQuery():object;
/**
* 获取当前是否处于正在跳转的状态
* H5 状态下始终为false
*/
get $lockStatus():boolean;
/**
* 动态设置拦截状态
*/
set $lockStatus(status:boolean);
/**动态的导航到一个新 URL 保留浏览历史
* navigateTo
* @param {Object} rule
*/
push(rule: Location | string): void;
/**动态的导航到一个新 URL 关闭当前页面,跳转到的某个页面。
* redirectTo
* @param {Object} rule
*/
replace(rule:Location | string):void;
/**动态的导航到一个新 URL 关闭所有页面,打开到应用内的某个页面
* reLaunch
* @param {Object} rule
*/
replaceAll(rule:Location | string):void;
/**动态的导航到一个新 url 关闭所有页面,打开到应用内的某个tab
* @param {Object} rule
*/
pushTab(rule:Location | string) :void;
/**
* 返回到指定层级页面上
*/
back(backLayer?:number,delta?:Object):void
/**
* 获取当前页面下的 Route 信息
* @param {Object} Vim 当前开发者可以传递一个 vue 组件对象 来获取当前下的 Route 信息
*/
getPageRoute(Vim?:Component) : Route
/**
* 注册的全局前置生命周期
* @param hooks 注册的全局前置生命周期函数
*/
beforeEach(hooks:Function) : Function
/**
* 注册的全局后置生命周期
* @param hooks 注册的全局后置生命周期函数
*/
afterEach(hooks:Function) : Function
static install:PluginFunction<never>
}
declare module "vue/types/vue" {
interface Vue {
$Router: Router;
$Route: Route;
}
}
export default Router;
export {
RouterMount,
Location,
Route,
Animation,
H5,
APP,
RouteConfig,
RouterOptions
}
\ No newline at end of file \ No newline at end of file
import Vue, { ComponentOptions,PluginFunction, AsyncComponent } from "vue";
type Component = ComponentOptions<Vue> | typeof Vue | AsyncComponent;
type Dictionary<T> = { [key: string]: T };
type Position = { x: number; y: number };
type PositionResult = Position | { selector: string; offset?: Position } | void;
type NAVTYPE= 'push' | 'replace' | 'replaceAll' | 'pushTab'
interface Location {
name?: string;
path?: string;
query?: Dictionary<string | (string | null)[] | null | undefined>;
params?: Dictionary<string>;
NAVTYPE?: NAVTYPE;
}
interface Route {
path: string;
name?: string;
params?: any;
query?: any;
beforeEnter?:(to:Route, from:Route, next:Function) => void;
meta?: any; //其他格外参数
}
interface Animation{
animationType?:string;
animationDuration?:number;
}
interface H5{
rewriteFun?:boolean; //是否对uni-app reLaunch/navigateBack 两个方法重写 处理uni刷新直接返回到首页和触发路由守卫
paramsToQuery?: boolean; //h5端上通过params传参时规则是vue-router 刷新会丢失 开启此开关将变成?连接的方式
loading?: boolean; //是否显示加载动画
hinderTab?: boolean; //是否拦截uni-app自带底部菜单 TODO
vueRouterDev?: boolean; //完全使用采用vue-router的开发模式
useUniConfig?: boolean; //是否采用在pages.json下的所有页面配置信息,false时需开发者自行设置页面
keepUniIntercept?: boolean; //保留uni-app使用vue-router的拦截器
vueNext?: boolean; //在next管道函数中是否获取vueRouter next的原本参数
replaceStyle?: boolean; //是否对resetStyle函数中返回的style节点进行全部替换,否则为追加
resetStyle?: () => Object; //自定义加载样式函数 可返回一个包涵 html、style、script 的对象来重置Router内置的加载动画
mode?: string;
base?: string;
linkActiveClass?: string;
linkExactActiveClass?: string;
scrollBehavior?: (to:Route, from:Route, savedPostion:Position|void) => PositionResult | Promise<PositionResult>,
fallback?: boolean,
}
interface APP{
holdTabbar?:boolean; //是否开启底部菜单拦截
rewriteFun?:boolean; //是否对uni-app 下的chooseLocation/openLocation 两个方法重写 目的是隐藏和显示拦截tabbar
loddingPageStyle?:()=>Object; //当前等待页面的样式 必须返回一个json
loddingPageHook?:()=>void; //刚刚打开页面处于等待状态,会触发此事件
holdTabbarStyle?:()=>Object;
animation?:Animation; //页面切换动画
switchPageOutTime?:number, //最高能忍耐的页面切换时间 达到此时间 不管切换有没有完成都会显示页面出来 这对启动页帮助很大
}
interface RouteConfig {
path: string; //pages.json中的path 必须加上 '/' 开头
component?: Component; //H5端可用
name?: string; // 命名路由
components?: { [name: string]: Component }; // 命名视图组件,H5端可用
redirect?: string | Location | Function; //H5端可用
props?: boolean | Object | Function; //H5端可用
aliasPath?:string; //h5端 设置一个别名路径来替换 uni-app的默认路径
alias?: string | Array<string>; //H5端可用
children?: Array<RouteConfig>; // 嵌套路由,H5端可用
beforeEnter?: (to: Route, from: Route, next: Function) => void; //路由元守卫
meta?: any; //其他格外参数
}
interface RouterOptions{
h5?:H5;
APP?:APP;
debugger?: boolean; //是否处于开发阶段 设置为true则打印日志
encodeURI?: boolean; //是否对url传递的参数进行编码
routerBeforeEach?: () => Object; //router 前置路由函数 每次触发跳转前先会触发此函数
routerAfterEach?: () => Object; //router 后置路由函数 每次触发跳转后会触发此函数
routes?: RouteConfig[];
}
export {
PluginFunction,
Component,
Location,
Route,
Animation,
H5,
APP,
RouteConfig,
RouterOptions
}
\ No newline at end of file \ No newline at end of file
export const builtIn = [{
path: '/preview-image',
name: 'previewImage',
component: {
render: () => {},
},
}, {
path: '/choose-location',
name: 'chooseLocation',
component: {
render: () => {},
},
}, {
path: '/open-location',
name: 'openLocation',
component: {
render: () => {},
},
}]; // uni-app内置路由
export const vuelifeHooks = { // vueRouter的原始生命周期
beforeHooks: [],
afterHooks: [],
};
export const vueMount = [];// 使用内部对象保留实例化下的appVue,并使用Router进行挂载触发第一次路由钩子
/**
* 实现一个继承的 数组类 代理掉 vue-router 生命钩子的数据
*/
class MyArray extends Array {
constructor(Router, vueOldHooks, hookFun) {
super();
this.Router = Router;
this.vueOldHooks = vueOldHooks;
this.hookFun = hookFun;
}
push(v) {
this.vueOldHooks.splice(0, 1, v);// 把vue-router路由生命钩子保存起来
this[this.length] = (to, from, next) => {
this.hookFun(to, from, next, this.Router);
};
}
}
export default MyArray;
import { afterHooks, beforeHooks, registerRouter } from './concat';
import { fromatRoutes } from './util';
import { err, warn } from '../helpers/warn';
import { proxyEachHooks } from './proxy/proxy';
/**
* 重写掉H5端 uni-app原始存在的bug
*
* @param {Object} Router
*/
const rewriteUniFun = function (Router) {
if (Router.CONFIG.h5.rewriteFun === false) { // 不需要重写
return false;
}
uni.reLaunch = function ({
url,
}) {
if (url === '/') {
warn('H5端 uni.reLaunch(\'/\')时 默认被重写了! 你可以使用 this.$Router.replaceAll() 或者 uni.reLaunch(\'/\'?xxx)');
// eslint-disable-next-line
if (history.length > 1) { // 只有在有历史记录的时候才返回 不然直接返回首页
return Router.back();
}
return Router.replaceAll('/');
}
const path = url.match(/^[^?]+|(\/)/)[0];
try {
const query = {};
url.replace(/([^?&]+)=([^?&]+)/g, (s, v, k) => {
query[v] = decodeURIComponent(k);
return `${k}=${v}`;
});
Router.replaceAll({
path,
query,
});
} catch (e) {
err(`${url}解析失败了.... 试试 this.$Router.replaceAll() 吧`);
}
};
uni.navigateBack = function (delta) {
let backLayer = delta;
if (delta.constructor === Object) { // 这种可能就只是uni-app自带的返回按钮,还有种可能就是开发者另类传递的
backLayer = 1;
}
Router.back(backLayer, delta);
};
};
/**
* 拦截并注册vueRouter中的生命钩子,路由表解析
* @param {Object} Router
* @param {vueRouter} vueRouter
*/
const init = function (Router, vueRouter) {
const CONFIG = Router.CONFIG.h5;
vueRouter.afterHooks = proxyEachHooks(Router, 'afterHooks', afterHooks);
vueRouter.beforeHooks = proxyEachHooks(Router, 'beforeHooks', beforeHooks);
const objVueRoutes = fromatRoutes(vueRouter.options.routes, false, {}); // 返回一个格式化好的routes 键值对的形式
const objSelfRoutes = fromatRoutes(Router.CONFIG.routes, true, CONFIG);
Router.vueRoutes = objVueRoutes; // 挂载vue-routes到当前的路由下
Router.selfRoutes = {
...Router.selfRoutes || {},
...objSelfRoutes,
}; // 挂载self-routes到当前路由下
Router.$route = vueRouter; // 挂载vue-router到$route
rewriteUniFun(Router); // 重新掉uniapp上的一些有异常的方法
registerRouter(Router, vueRouter, CONFIG.vueRouterDev);
};
export default init;
import { beforeEnterHooks } from '../concat';
import { vuelifeHooks } from '../base';
import MyArray from '../extends/myArray';
/**
* 通过 Object.defineProperty 代理一个对象主要是拦截beforeEnter 生命钩子
* @param {Router} Router 路由实例对象
* @param {Object} BeProxy 需要代理的路由表
*/
export const proxyBeforeEnter = function (Router, BeProxy) {
const proxyDc = Object.create(null);// 创建没有继承的属性
const BeProxyKeys = Object.keys(BeProxy);
for (let i = 0; i < BeProxyKeys.length; i += 1) {
const key = BeProxyKeys[i];
Object.defineProperty(proxyDc, key, {
enumerable: true,
configurable: true,
get() {
const value = BeProxy[key];
if (key == 'beforeEnter' && value !== undefined) {
return (to, from, next) => {
beforeEnterHooks(to, from, next, value, Router);
};
}
return value;
},
set(v) {
BeProxy[key] = v;
},
});
}
return proxyDc;
};
/**
* 在uni-app没有注入生命周期时先直接代理相关生命周期数组
* @param {Object} Router
* @param {Object} key
* @param {Funtion} hookFun
*/
export const proxyEachHooks = function (Router, key, hookFun) {
const vueOldHooks = vuelifeHooks[key];
return new MyArray(Router, vueOldHooks, hookFun);
};
import { err } from '../helpers/warn';
import { formatUserRule, strPathToObjPath } from './util';
/**
* @param {Object} replace vue-router的跳转方式
* @param {Object} rule 需要跳转到的路由匹配规则
* @param {Object} type 对应的官方跳转模式
*
* this 为当前 Router 实例
*/
const H5PushTo = function (replace, rule, type) {
if (this.$route == null) {
return err('h5端路由为就绪,请检查调用代码');
}
rule = formatUserRule(rule, this.selfRoutes, this.CONFIG);
const objPath = strPathToObjPath(rule);
objPath.type = type;
this.$route[replace](objPath);
};
export default H5PushTo;
插件市场安装的用户 你需要在你项目目录下执行 `npm init -y && npm install query-string -D`
\ No newline at end of file \ No newline at end of file
{
"description": "项目配置文件",
"packOptions": {
"ignore": []
},
"setting": {
"urlCheck": true,
"es6": true,
"enhance": false,
"postcss": true,
"preloadBackgroundData": false,
"minified": true,
"newFeature": false,
"coverView": true,
"nodeModules": false,
"autoAudits": false,
"showShadowRootInWxmlPanel": true,
"scopeDataCheck": false,
"uglifyFileName": false,
"checkInvalidKey": true,
"checkSiteMap": true,
"uploadWithSourceMap": true,
"compileHotReLoad": false,
"useMultiFrameRuntime": true,
"useApiHook": true,
"useApiHostProcess": false,
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
},
"enableEngineNative": false,
"bundle": false,
"useIsolateContext": true,
"useCompilerModule": true,
"userConfirmedUseCompilerModuleSwitch": false,
"userConfirmedBundleSwitch": false,
"packNpmManually": false,
"packNpmRelationList": [],
"minifyWXSS": true
},
"compileType": "miniprogram",
"libVersion": "2.16.0",
"appid": "wxc6d04e883f1cd397",
"projectname": "uView_Base%E6%A8%A1%E6%9D%BF",
"debugOptions": {
"hidedInDevtools": []
},
"scripts": {},
"staticServerOptions": {
"baseURL": "",
"servePath": ""
},
"isGameTourist": false,
"condition": {
"search": {
"list": []
},
"conversation": {
"list": []
},
"game": {
"list": []
},
"plugin": {
"list": []
},
"gamePlugin": {
"list": []
},
"miniprogram": {
"list": []
}
}
}
\ No newline at end of file \ No newline at end of file
import modules from './modules'
import Vue from 'vue'
import Router from '@/plugin/uni-simple-router/index.js'
Vue.use(Router)
//初始化
const router = new Router({
encodeURI:true,
routes: [...modules]//路由表
});
const whiteList = ['/pages/login/login']
//全局路由前置守卫
router.beforeEach((to, from, next) => {
next()
})
// 全局路由后置守卫
router.afterEach((to, from) => {
console.log("afterEach")
});
\ No newline at end of file \ No newline at end of file
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
\ No newline at end of file \ No newline at end of file
const routes = [
{
path: "/pages/login/login",
name: 'login',
meta: {
title: '登录',
},
},
{
//注意:path必须跟pages.json中的地址对应,最前面别忘了加'/'哦
path: '/pages/index/index',
name: 'index',
meta: {
title: '主页',
},
},
]
export default routes
\ No newline at end of file \ No newline at end of file
No preview for this file type

3.93 KB | W: | H:

15.2 KB | W: | H:

static/logo.png
static/logo.png
static/logo.png
static/logo.png
  • 2-up
  • Swipe
  • Onion skin
export default {
token: (state) => state.user.token,
siteData: (state) => state.site.siteData,
userData: (state) => state.user.userData,
userId: (state) => state.user.userData.id,
};
import Vue from 'vue';
import Vuex from 'vuex';
import getters from './getters';
import user from './modules/user';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
user,
},
getters,
});
// Vue.prototype.$store = store;
export default store;
\ No newline at end of file \ No newline at end of file
import { setToken, getToken, removeToken } from '@/utils/token';;
export default {
namespaced: true,
state() {
return {
userData: {},
token: getToken(),
};
},
mutations: {
setUserData(state, data) {
state.userData = data;
},
removeToken(state) {
state.token = '';
removeToken();
},
setToken(state, token) {
state.token = token;
setToken(token);
},
},
actions: {
// 获取用户详情
async getUserData({ commit }, { params = {}, options = {} } = {}) {
// console.log("userData", parseData);
commit('setUserData', options.token);
return parseData;
},
async logout({ commit }) {
commit('removeToken');
commit('setUserData', {});
},
},
};
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px'
})
</script>
<link rel="stylesheet" href="<%= BASE_URL %>static/index.css" />
</head>
<body>
<noscript>
<strong>本站点必须要开启JavaScript才能运行</strong>
</noscript>
<div id="app"></div>
</body>
</html>
/** /**
* 这里是uni-app内置的常用样式变量 * 下方引入的为uView UI的集成样式文件,为scss预处理器,其中包含了一些"u-"开头的自定义变量
* * uView自定义的css类名和scss变量,均以"u-"开头,不会造成冲突,请放心使用
* uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量
* 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App
*
*/ */
@import 'uview-ui/theme.scss';
/**
* 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能
*
* 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件
*/
/* 颜色变量 */
/* 行为相关颜色 */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;
/* 文字基本颜色 */
$uni-text-color:#333;//基本色
$uni-text-color-inverse:#fff;//反色
$uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080;
$uni-text-color-disable:#c0c0c0;
/* 背景颜色 */
$uni-bg-color:#ffffff;
$uni-bg-color-grey:#f8f8f8;
$uni-bg-color-hover:#f1f1f1;//点击状态颜色
$uni-bg-color-mask:rgba(0, 0, 0, 0.4);//遮罩颜色
/* 边框颜色 */
$uni-border-color:#c8c7cc;
/* 尺寸变量 */
/* 文字尺寸 */
$uni-font-size-sm:12px;
$uni-font-size-base:14px;
$uni-font-size-lg:16;
/* 图片尺寸 */
$uni-img-size-sm:20px;
$uni-img-size-base:26px;
$uni-img-size-lg:40px;
/* Border Radius */
$uni-border-radius-sm: 2px;
$uni-border-radius-base: 3px;
$uni-border-radius-lg: 6px;
$uni-border-radius-circle: 50%;
/* 水平间距 */
$uni-spacing-row-sm: 5px;
$uni-spacing-row-base: 10px;
$uni-spacing-row-lg: 15px;
/* 垂直间距 */
$uni-spacing-col-sm: 4px;
$uni-spacing-col-base: 8px;
$uni-spacing-col-lg: 12px;
/* 透明度 */
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
/* 文章场景相关 */
$uni-color-title: #2C405A; // 文章标题颜色
$uni-font-size-title:20px;
$uni-color-subtitle: #555555; // 二级标题颜色
$uni-font-size-subtitle:26px;
$uni-color-paragraph: #3F536E; // 文章段落颜色
$uni-font-size-paragraph:15px;
/**
* http接口API集中管理
*/
const install = (Vue, vm) => {
// 小程序通用的接口
let wxLogin = (code) => vm.$u.get('/wxLogin/' + code);
let wxGetUserInfo = (params = {}) => vm.$u.post('/wxGetUserInfo', params);
let wxGetPhoneNumber = (params = {}) => vm.$u.post('/wxGetPhoneNumber', params);
vm.$u.api = {
wxLogin,
wxGetUserInfo,
wxGetPhoneNumber,
}
}
export default {
install
}
import config from '@/config.js'
import common from '@/utils/wxApplet/common.js'
/**
* http拦截器
*/
const install = (Vue, vm) => {
// 自定义配置参数
Vue.prototype.$u.http.setConfig({
baseUrl: config.HTTP_REQUEST_URL,
loadingText: '努力加载中~',
loadingTime: 800,
// ......
});
// 请求拦截
Vue.prototype.$u.http.interceptor.request = (configs) => {
configs.header[config.TOKEN_NAME] = vm.$store.state.vuex_token ? vm.$store.state.vuex_token : "";
return configs;
}
// 响应拦截
Vue.prototype.$u.http.interceptor.response = (res) => {
// res为服务端返回值,有code、message、data等字段
if (res.code == 10000) {
return res.data;
}
// else if (res.code == -101) {
// // Token快过期,替换新的token
// vm.$u.vuex('vuex_token', res.data.token);
// // 无痛刷新token
// return vm.$u.post(Vue.prototype.$u.http.options.url).then(result => {
// return result;
// })
// }
else if (res.code == 10006 || res.code == 10007) {
// Token已过期|加入黑名单|Token校验失败,则需重新进入登录页登录
common.logout();
uni.reLaunch({
url: '/pages/login/login'
});
return false;
} else {
// 如果返回false,则会调用Promise的reject回调
if (res.message) {
vm.$u.toast(res.message)
} else {
vm.$u.toast(res)
}
return false;
}
}
}
export default {
install
}
This diff could not be displayed because it is too large.
import OSS from 'ali-oss';
console.log(OSS)
const ossClient = new OSS({
region: "oss-cn-beijing",
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
accessKeyId: "LTAI5tANJ9i8sw31JPGBDTaz",
accessKeySecret: "uFmxSaBsA9GaENO6XyIIoQaVHcIwIx",
// 从STS服务获取的安全令牌(SecurityToken)。
stsToken: "yourSecurityToken",
// 填写Bucket名称。
bucket: "myfrist-carol",
});
export default ossClient;
\ No newline at end of file \ No newline at end of file
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var base64DecodeChars = new Array(
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
function encode(str) {
var out, i, len;
var c1, c2, c3;
len = str.length;
i = 0;
out = "";
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}
function decode(str) {
var c1, c2, c3, c4;
var i, len, out;
len = str.length;
i = 0;
out = "";
while (i < len) {
/* c1 */
do {
c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c1 == -1);
if (c1 == -1)
break;
/* c2 */
do {
c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c2 == -1);
if (c2 == -1)
break;
out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
/* c3 */
do {
c3 = str.charCodeAt(i++) & 0xff;
if (c3 == 61)
return out;
c3 = base64DecodeChars[c3];
} while (i < len && c3 == -1);
if (c3 == -1)
break;
out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
/* c4 */
do {
c4 = str.charCodeAt(i++) & 0xff;
if (c4 == 61)
return out;
c4 = base64DecodeChars[c4];
} while (i < len && c4 == -1);
if (c4 == -1)
break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
}
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
function utf8to16(str) {
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while (i < len) {
c = str.charCodeAt(i++);
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += str.charAt(i - 1);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
module.exports = {
encode: encode,
decode: decode,
utf16to8: utf16to8,
utf8to16: utf8to16
}
import config from '@/config.js'
// 在h5端上传涉及到跨域,需在阿里云上配置跨域规则才能正常使用
module.exports = {
uploadImageUrl: config.OSS_DOMAIN + '/', // 默认存在根目录后面要跟个'/' (在你当前小程序的后台的uploadFile 合法域名也要配上这个域名)
AccessKeySecret: config.ACCESSKEYSECRET, // AccessKeySecret 去你的阿里云上控制台上找
OSSAccessKeyId: config.ACCESSKEYID, // AccessKeyId 去你的阿里云上控制台上找
timeout: 87600 // 这个是上传文件时Policy的失效时间
}
const Crypto = {};
(function() {
var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Global Crypto object
// window.Crypto = {};
// Crypto utilities
var util = Crypto.util = {
// Bit-wise rotate left
rotl: function(n, b) {
return (n << b) | (n >>> (32 - b));
},
// Bit-wise rotate right
rotr: function(n, b) {
return (n << (32 - b)) | (n >>> b);
},
// Swap big-endian to little-endian and vice versa
endian: function(n) {
// If number given, swap endian
if (n.constructor == Number) {
return util.rotl(n, 8) & 0x00FF00FF |
util.rotl(n, 24) & 0xFF00FF00;
}
// Else, assume array and swap all items
for (var i = 0; i < n.length; i++)
n[i] = util.endian(n[i]);
return n;
},
// Generate an array of any length of random bytes
randomBytes: function(n) {
for (var bytes = []; n > 0; n--)
bytes.push(Math.floor(Math.random() * 256));
return bytes;
},
// Convert a string to a byte array
stringToBytes: function(str) {
var bytes = [];
for (var i = 0; i < str.length; i++)
bytes.push(str.charCodeAt(i));
return bytes;
},
// Convert a byte array to a string
bytesToString: function(bytes) {
var str = [];
for (var i = 0; i < bytes.length; i++)
str.push(String.fromCharCode(bytes[i]));
return str.join("");
},
// Convert a string to big-endian 32-bit words
stringToWords: function(str) {
var words = [];
for (var c = 0, b = 0; c < str.length; c++, b += 8)
words[b >>> 5] |= str.charCodeAt(c) << (24 - b % 32);
return words;
},
// Convert a byte array to big-endian 32-bits words
bytesToWords: function(bytes) {
var words = [];
for (var i = 0, b = 0; i < bytes.length; i++, b += 8)
words[b >>> 5] |= bytes[i] << (24 - b % 32);
return words;
},
// Convert big-endian 32-bit words to a byte array
wordsToBytes: function(words) {
var bytes = [];
for (var b = 0; b < words.length * 32; b += 8)
bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
return bytes;
},
// Convert a byte array to a hex string
bytesToHex: function(bytes) {
var hex = [];
for (var i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join("");
},
// Convert a hex string to a byte array
hexToBytes: function(hex) {
var bytes = [];
for (var c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
},
// Convert a byte array to a base-64 string
bytesToBase64: function(bytes) {
// Use browser-native function if it exists
if (typeof btoa == "function") return btoa(util.bytesToString(bytes));
var base64 = [],
overflow;
for (var i = 0; i < bytes.length; i++) {
switch (i % 3) {
case 0:
base64.push(base64map.charAt(bytes[i] >>> 2));
overflow = (bytes[i] & 0x3) << 4;
break;
case 1:
base64.push(base64map.charAt(overflow | (bytes[i] >>> 4)));
overflow = (bytes[i] & 0xF) << 2;
break;
case 2:
base64.push(base64map.charAt(overflow | (bytes[i] >>> 6)));
base64.push(base64map.charAt(bytes[i] & 0x3F));
overflow = -1;
}
}
// Encode overflow bits, if there are any
if (overflow != undefined && overflow != -1)
base64.push(base64map.charAt(overflow));
// Add padding
while (base64.length % 4 != 0) base64.push("=");
return base64.join("");
},
// Convert a base-64 string to a byte array
base64ToBytes: function(base64) {
// Use browser-native function if it exists
if (typeof atob == "function") return util.stringToBytes(atob(base64));
// Remove non-base-64 characters
base64 = base64.replace(/[^A-Z0-9+\/]/ig, "");
var bytes = [];
for (var i = 0; i < base64.length; i++) {
switch (i % 4) {
case 1:
bytes.push((base64map.indexOf(base64.charAt(i - 1)) << 2) |
(base64map.indexOf(base64.charAt(i)) >>> 4));
break;
case 2:
bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0xF) << 4) |
(base64map.indexOf(base64.charAt(i)) >>> 2));
break;
case 3:
bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & 0x3) << 6) |
(base64map.indexOf(base64.charAt(i))));
break;
}
}
return bytes;
}
};
// Crypto mode namespace
Crypto.mode = {};
})();
module.exports = Crypto;
import Crypto from './crypto.js'
(function() {
// Shortcut
var util = Crypto.util;
Crypto.HMAC = function(hasher, message, key, options) {
// Allow arbitrary length keys
key = key.length > hasher._blocksize * 4 ?
hasher(key, {
asBytes: true
}) :
util.stringToBytes(key);
// XOR keys with pad constants
var okey = key,
ikey = key.slice(0);
for (var i = 0; i < hasher._blocksize * 4; i++) {
okey[i] ^= 0x5C;
ikey[i] ^= 0x36;
}
var hmacbytes = hasher(util.bytesToString(okey) +
hasher(util.bytesToString(ikey) + message, {
asString: true
}), {
asBytes: true
});
return options && options.asBytes ? hmacbytes :
options && options.asString ? util.bytesToString(hmacbytes) :
util.bytesToHex(hmacbytes);
};
})();
module.exports = Crypto;
import Crypto from './crypto.js'
(function() {
// Shortcut
var util = Crypto.util;
// Public API
var SHA1 = Crypto.SHA1 = function(message, options) {
var digestbytes = util.wordsToBytes(SHA1._sha1(message));
return options && options.asBytes ? digestbytes :
options && options.asString ? util.bytesToString(digestbytes) :
util.bytesToHex(digestbytes);
};
// The core
SHA1._sha1 = function(message) {
var m = util.stringToWords(message),
l = message.length * 8,
w = [],
H0 = 1732584193,
H1 = -271733879,
H2 = -1732584194,
H3 = 271733878,
H4 = -1009589776;
// Padding
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >>> 9) << 4) + 15] = l;
for (var i = 0; i < m.length; i += 16) {
var a = H0,
b = H1,
c = H2,
d = H3,
e = H4;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = m[i + j];
else {
var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
w[j] = (n << 1) | (n >>> 31);
}
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
(H1 ^ H2 ^ H3) - 899497514);
H4 = H3;
H3 = H2;
H2 = (H1 << 30) | (H1 >>> 2);
H1 = H0;
H0 = t;
}
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += e;
}
return [H0, H1, H2, H3, H4];
};
// Package private blocksize
SHA1._blocksize = 16;
})();
module.exports = Crypto;
// base64,Hmac,Sha1,Crypto 相关算法
import config from './config.js';
import base64 from './base64.js';
import Hmac from './hmac.js';
import Sha1 from './sha1.js';
import Crypto from './crypto.js';
/**
* 上传文件到阿里云oss
* @param {string} filePath 图片的本地资源路径
* @param {string} dir 表示要传到哪个目录下
* @return 完整的图片地址
*/
const uploadFile = function(filePath, dir) {
return new Promise((resolve, reject) => {
if (!filePath || filePath.length < 9) {
uni.showModal({
title: '图片错误',
content: '请重试',
showCancel: false,
})
reject('图片错误');
}
console.log('上传图片中...');
// #ifdef H5
// 图片名字 可以自行定义
let aliyunFileKey = dir + '.png';
// #endif
// #ifndef H5
// 获取上传的文件类型
let fileTypeIndex = filePath.lastIndexOf('.');
let fileType = filePath.substring(fileTypeIndex);
let aliyunFileKey = dir + fileType;
// #endif
const aliyunServerURL = config.uploadImageUrl; // OSS地址,需要https
const accessid = config.OSSAccessKeyId;
const policyBase64 = getPolicyBase64();
const signature = getSignature(policyBase64); // 获取签名
uni.uploadFile({
url: aliyunServerURL, // 开发者服务器url
filePath: filePath, // 要上传文件资源的路径
name: 'file', // 必须填file
formData: {
'key': aliyunFileKey,
'policy': policyBase64,
'OSSAccessKeyId': accessid,
'success_action_status': '200', // 让服务端返回200, 不然默认会返回204
'signature': signature,
},
success: function(res) {
if (res.statusCode != 200) {
reject(new Error('上传错误:' + JSON.stringify(res)));
}
resolve(aliyunServerURL + aliyunFileKey);
},
fail: function(err) {
err.domainName = aliyunServerURL;
reject(err);
},
})
});
}
const getPolicyBase64 = function() {
let date = new Date();
date.setHours(date.getHours() + config.timeout);
let srcT = date.toISOString();
const policyText = {
"expiration": '2099-01-01T12:00:00.000Z', //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
"conditions": [
["content-length-range", 0, 5242880] // 设置上传文件的大小限制(5m)
]
};
const policyBase64 = base64.encode(JSON.stringify(policyText));
return policyBase64;
}
// 生成签名
const getSignature = function(policyBase64) {
const accesskey = config.AccessKeySecret;
const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
asBytes: true
});
const signature = Crypto.util.bytesToBase64(bytes);
return signature;
}
module.exports = uploadFile;
export const setToken = (data) => {
uni.setStorageSync('token', data);
};
export const getToken = () => uni.getStorageSync('token');
export const removeToken = () => {
uni.removeStorageSync('token');
};
\ No newline at end of file \ No newline at end of file
import Vue from 'vue';
const login = () => {
return new Promise((resolve, reject) => {
uni.login({
provider: 'weixin',
success: (res) => {
Vue.prototype.$u.api.wxLogin(res.code).then(res => {
Vue.prototype.$u.vuex('vuex_openid', res.openid);
resolve(true)
}).catch(err => {
resolve(false)
})
}
})
})
}
/**
* 获取登录凭证
* @return {boolean} true:已过期、false:未过期
*/
const wxLogin = () => {
return new Promise((resolve, reject) => {
uni.checkSession({
success: res => {
//session_key 未过期,并且在本生命周期一直有效
let openid = Vue.prototype.$store.state.vuex_openid;
if (!openid) {
login().then(() => {
resolve(true)
})
} else {
resolve(false)
}
},
fail: err => {
// session_key 已经失效,需要重新执行登录流程
login().then(() => {
resolve(true)
})
}
})
})
}
/**
* 退出登录
*/
const logout = () => {
return new Promise((resolve, reject) => {
Vue.prototype.$u.vuex('vuex_token', '');
Vue.prototype.$u.vuex('vuex_userInfo', '');
Vue.prototype.$u.vuex('vuex_phone', '');
resolve(true);
})
}
/**
* 获取用户基础信息(昵称、头像等)
* @return {object} { true: '允许授权|已授权过了 可以继续往下执行其他业务逻辑', false: '拒绝授权|异常' }
*/
const getUserProfile = () => {
return new Promise((resolve, reject) => {
let vuex_userInfo = Vue.prototype.$store.state.vuex_userInfo,
openid = Vue.prototype.$store.state.vuex_openid;
if (!openid) {
Vue.prototype.$u.toast('openid为空!请先调用login接口');
resolve(false);
} else {
if (!vuex_userInfo) {
uni.getUserProfile({
// 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
desc: '用于完善会员资料',
success: (res) => {
// 允许授权
Vue.prototype.$u.api.wxGetUserInfo({
encryptedData: res.encryptedData,
iv: res.iv,
openid
}).then(userInfo => {
Vue.prototype.$u.vuex('vuex_userInfo', userInfo);
resolve(true);
}).catch(err => {
Vue.prototype.$u.toast(err.errMsg);
resolve(false);
});
},
fail: (err) => {
// 拒绝授权|其他异常
if (err.errMsg != "getUserProfile:fail auth deny") {
Vue.prototype.$u.toast(err.errMsg);
}
resolve(false);
}
})
} else {
// 已经授权过了
resolve(true)
}
}
})
}
/**
* 微信手机号快捷登录
* @param {object} e 回调函数的整个参数
* @return {object} { true: '允许授权|已授权过了 可以继续往下执行其他业务逻辑', false: '拒绝授权' }
*/
const getPhoneNumber = (e) => {
return new Promise((resolve, reject) => {
let detail = e.detail;
if (detail.errMsg == "getPhoneNumber:ok") {
let openid = Vue.prototype.$store.state.vuex_openid;
if (!openid) {
Vue.prototype.$u.toast('openid为空!请先调用login接口');
resolve(false);
} else {
wxLogin().then(() => {
Vue.prototype.$u.api.wxGetPhoneNumber({
encryptedData: detail.encryptedData,
iv: detail.iv,
openid
}).then(data => {
Vue.prototype.$u.vuex('vuex_phone', data.phones);
Vue.prototype.$u.vuex('vuex_token', data.token);
Vue.prototype.$u.vuex('vuex_userInfo', data.userInfo);
resolve(true);
})
})
}
} else {
// 拒绝授权
if (detail.errMsg == 'getPhoneNumber:fail user deny' || detail.errMsg == 'getPhoneNumber:fail:user deny') {
Vue.prototype.$u.toast('授权登录后才能体验完整的功能哦', 2500);
} else if (detail.errMsg == 'getPhoneNumber:fail no permission') {
Vue.prototype.$u.toast('该小程序暂无权限获取用户的手机号!', 2500);
}
resolve(false);
}
})
}
export default {
wxLogin,
logout,
getUserProfile,
getPhoneNumber
}
import Vue from 'vue';
import jweixin from './jweixin-1.6.0.js';
export default {
/**
* 判断当前运行环境是否在【微信客户端】中
* @return true|false
*/
isWechat() {
let ua = window.navigator.userAgent.toLowerCase();
if (ua.match(/micromessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
},
/**
* 初始化jssdk配置
* 所有需要使用JS-SDK的页面必须先注入配置信息,否则将无法调用(同一个url仅需调用一次)
* @param url 页面完整地址(但不包括'#'hash后面的部分)
*/
initJssdkConfig(url) {
return new Promise((resolve, reject) => {
Vue.prototype.$u.get('/H5Common/getSignPackage', {
url: encodeURIComponent(url)
}).then(res => {
jweixin.config({
debug: false, // 开启调试模式
appId: res.data.appId, // 必填,公众号的唯一标识
timestamp: res.data.timestamp, // 必填,生成签名的时间戳
nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
signature: res.data.signature, // 必填,签名
jsApiList: [ // 必填,需要使用的JS接口列表
'hideMenuItems',
'updateTimelineShareData',
'updateAppMessageShareData',
'chooseWXPay'
]
});
resolve();
})
})
},
/**
* 在需要自定义分享的页面中调用
* @param {Object} data {"title":"分享标题","desc":"分享描述","imgUrl":"分享图标"}
*/
share(data) {
if (!this.isWechat()) return;
let url = window.location.href.split('#')[0];
// 每次都需要重新初始化配置,才可以进行分享
this.initJssdkConfig(url).then(() => {
jweixin.ready(() => {
// jweixin.hideMenuItems({
// menuList: [ // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3
// 'menuItem:copyUrl' // 复制链接
// ]
// });
if (url.indexOf('?') != -1) {
url += '&uid=' + uni.getStorageSync('uid');
} else {
url += '?uid=' + uni.getStorageSync('uid');
}
// 分享给朋友
jweixin.updateAppMessageShareData({
title: data.title, // 分享标题
desc: data.desc, // 分享描述
link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: data.imgUrl, // 分享图标
});
// 分享到朋友圈
jweixin.updateTimelineShareData({
title: data.title, // 分享标题
link: url, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: data.imgUrl, // 分享图标
});
});
jweixin.error(err => {
console.error('Jssdk失败验证==', err)
Vue.prototype.$u.toast('Jssdk失败验证=='.err);
});
});
},
/**
* 微信支付
* @param {Object} data 支付所需的参数
*/
wxPay(data) {
return new Promise((resolve, reject) => {
let url = window.location.href.split('#')[0];
this.initJssdkConfig(url).then(() => {
jweixin.ready(() => {
jweixin.chooseWXPay({
timestamp: data.timeStamp, // 支付签名时间戳
nonceStr: data.nonceStr, // 支付签名随机串,不长于 32 位
package: data.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
signType: data.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: data.paySign, // 支付签名
success(res) {
resolve(res);
},
fail(err) {
reject(err);
}
});
});
jweixin.error(err => {
console.error('支付失败验证==', err)
Vue.prototype.$u.toast('支付失败验证=='.err);
});
})
});
}
}
MIT License
Copyright (c) 2023 www.uviewui.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<p align="center">
<img alt="logo" src="https://uviewui.com/common/logo.png" width="120" height="120" style="margin-bottom: 10px;">
</p>
<h3 align="center" style="margin: 30px 0 30px;font-weight: bold;font-size:40px;">uView</h3>
<h3 align="center">多平台快速开发的UI框架</h3>
## 说明
uView UI,是[uni-app](https://uniapp.dcloud.io/)生态优秀的UI框架,全面的组件和便捷的工具会让您信手拈来,如鱼得水
## 特性
- 兼容安卓,iOS,微信小程序,H5,QQ小程序,百度小程序,支付宝小程序,头条小程序
- 60+精选组件,功能丰富,多端兼容,让您快速集成,开箱即用
- 众多贴心的JS利器,让您飞镖在手,召之即来,百步穿杨
- 众多的常用页面和布局,让您专注逻辑,事半功倍
- 详尽的文档支持,现代化的演示效果
- 按需引入,精简打包体积
## 安装
```bash
# npm方式安装
npm i uview-ui
```
## 快速上手
1. `main.js`引入uView库
```js
// main.js
import uView from 'uview-ui';
Vue.use(uView);
```
2. `App.vue`引入基础样式(注意style标签需声明scss属性支持)
```css
/* App.vue */
<style lang="scss">
@import "uview-ui/index.scss";
</style>
```
3. `uni.scss`引入全局scss变量文件
```css
/* uni.scss */
@import "uview-ui/theme.scss";
```
4. `pages.json`配置easycom规则(按需引入)
```js
// pages.json
{
"easycom": {
// npm安装的方式不需要前面的"@/",下载安装的方式需要"@/"
// npm安装方式
"^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"
// 下载安装方式
// "^u-(.*)": "@/uview-ui/components/u-$1/u-$1.vue"
},
// 此为本身已有的内容
"pages": [
// ......
]
}
```
请通过[快速上手](https://uviewui.com/components/quickstart.html)了解更详细的内容
## 使用方法
配置easycom规则后,自动按需引入,无需`import`组件,直接引用即可。
```html
<template>
<u-button>按钮</u-button>
</template>
```
请通过[快速上手](https://uviewui.com/components/quickstart.html)了解更详细的内容
## 链接
- [官方文档](https://uviewui.com/)
- [更新日志](https://uviewui.com/components/changelog.html)
- [升级指南](https://uviewui.com/components/changelog.html)
- [关于我们](https://uviewui.com/cooperation/about.html)
## 预览
您可以通过**微信**扫码,查看最佳的演示效果。
<br>
<br>
<img src="https://uviewui.com/common/weixin_mini_qrcode.png" width="220" height="220" >
<!-- ## 捐赠uView的研发
uView文档和源码全部开源免费,如果您认为uView帮到了您的开发工作,您可以捐赠uView的研发工作,捐赠无门槛,哪怕是一杯可乐也好(相信这比打赏主播更有意义)。
<img src="https://uviewui.com/common/wechat.png" width="220" >
<img style="margin-left: 100px;" src="https://uviewui.com/common/alipay.png" width="220" >
-->
## 版权信息
uView遵循[MIT](https://en.wikipedia.org/wiki/MIT_License)开源协议,意味着您无需支付任何费用,也无需授权,即可将uView应用到您的产品中。
<template>
<u-popup mode="bottom" :border-radius="borderRadius" :popup="false" v-model="value" :maskCloseAble="maskCloseAble"
length="auto" :safeAreaInsetBottom="safeAreaInsetBottom" @close="popupClose" :z-index="uZIndex">
<view class="u-tips u-border-bottom" v-if="tips.text" :style="[tipsStyle]">
{{tips.text}}
</view>
<block v-for="(item, index) in list" :key="index">
<view
@touchmove.stop.prevent
@tap="itemClick(index)"
:style="[itemStyle(index)]"
class="u-action-sheet-item u-line-1"
:class="[index < list.length - 1 ? 'u-border-bottom' : '']"
:hover-stay-time="150"
>
<text>{{item.text}}</text>
<text class="u-action-sheet-item__subtext u-line-1" v-if="item.subText">{{item.subText}}</text>
</view>
</block>
<view class="u-gab" v-if="cancelBtn">
</view>
<view @touchmove.stop.prevent class="u-actionsheet-cancel u-action-sheet-item" hover-class="u-hover-class"
:hover-stay-time="150" v-if="cancelBtn" @tap="close">{{cancelText}}</view>
</u-popup>
</template>
<script>
/**
* actionSheet 操作菜单
* @description 本组件用于从底部弹出一个操作菜单,供用户选择并返回结果。本组件功能类似于uni的uni.showActionSheetAPI,配置更加灵活,所有平台都表现一致。
* @tutorial https://www.uviewui.com/components/actionSheet.html
* @property {Array<Object>} list 按钮的文字数组,见官方文档示例
* @property {Object} tips 顶部的提示文字,见官方文档示例
* @property {String} cancel-text 取消按钮的提示文字
* @property {Boolean} cancel-btn 是否显示底部的取消按钮(默认true)
* @property {Number String} border-radius 弹出部分顶部左右的圆角值,单位rpx(默认0)
* @property {Boolean} mask-close-able 点击遮罩是否可以关闭(默认true)
* @property {Boolean} safe-area-inset-bottom 是否开启底部安全区适配(默认false)
* @property {Number String} z-index z-index值(默认1075)
* @property {String} cancel-text 取消按钮的提示文字
* @event {Function} click 点击ActionSheet列表项时触发
* @event {Function} close 点击取消按钮时触发
* @example <u-action-sheet :list="list" @click="click" v-model="show"></u-action-sheet>
*/
export default {
name: "u-action-sheet",
props: {
// 点击遮罩是否可以关闭actionsheet
maskCloseAble: {
type: Boolean,
default: true
},
// 按钮的文字数组,可以自定义颜色和字体大小,字体单位为rpx
list: {
type: Array,
default () {
// 如下
// return [{
// text: '确定',
// color: '',
// fontSize: ''
// }]
return [];
}
},
// 顶部的提示文字
tips: {
type: Object,
default () {
return {
text: '',
color: '',
fontSize: '26'
}
}
},
// 底部的取消按钮
cancelBtn: {
type: Boolean,
default: true
},
// 是否开启底部安全区适配,开启的话,会在iPhoneX机型底部添加一定的内边距
safeAreaInsetBottom: {
type: Boolean,
default: false
},
// 通过双向绑定控制组件的弹出与收起
value: {
type: Boolean,
default: false
},
// 弹出的顶部圆角值
borderRadius: {
type: [String, Number],
default: 0
},
// 弹出的z-index值
zIndex: {
type: [String, Number],
default: 0
},
// 取消按钮的文字提示
cancelText: {
type: String,
default: '取消'
}
},
computed: {
// 顶部提示的样式
tipsStyle() {
let style = {};
if (this.tips.color) style.color = this.tips.color;
if (this.tips.fontSize) style.fontSize = this.tips.fontSize + 'rpx';
return style;
},
// 操作项目的样式
itemStyle() {
return (index) => {
let style = {};
if (this.list[index].color) style.color = this.list[index].color;
if (this.list[index].fontSize) style.fontSize = this.list[index].fontSize + 'rpx';
// 选项被禁用的样式
if (this.list[index].disabled) style.color = '#c0c4cc';
return style;
}
},
uZIndex() {
// 如果用户有传递z-index值,优先使用
return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
}
},
methods: {
// 点击取消按钮
close() {
// 发送input事件,并不会作用于父组件,而是要设置组件内部通过props传递的value参数
// 这是一个vue发送事件的特殊用法
this.popupClose();
this.$emit('close');
},
// 弹窗关闭
popupClose() {
this.$emit('input', false);
},
// 点击某一个item
itemClick(index) {
// disabled的项禁止点击
if(this.list[index].disabled) return;
this.$emit('click', index);
this.$emit('input', false);
}
}
}
</script>
<style lang="scss" scoped>
@import "../../libs/css/style.components.scss";
.u-tips {
font-size: 26rpx;
text-align: center;
padding: 34rpx 0;
line-height: 1;
color: $u-tips-color;
}
.u-action-sheet-item {
@include vue-flex;;
line-height: 1;
justify-content: center;
align-items: center;
font-size: 32rpx;
padding: 34rpx 0;
flex-direction: column;
}
.u-action-sheet-item__subtext {
font-size: 24rpx;
color: $u-tips-color;
margin-top: 20rpx;
}
.u-gab {
height: 12rpx;
background-color: rgb(234, 234, 236);
}
.u-actionsheet-cancel {
color: $u-main-color;
}
</style>
<template>
<view class="u-alert-tips" v-if="show" :class="[
!show ? 'u-close-alert-tips': '',
type ? 'u-alert-tips--bg--' + type + '-light' : '',
type ? 'u-alert-tips--border--' + type + '-disabled' : '',
]" :style="{
backgroundColor: bgColor,
borderColor: borderColor
}">
<view class="u-icon-wrap">
<u-icon v-if="showIcon" :name="uIcon" :size="description ? 40 : 32" class="u-icon" :color="uIconType" :custom-style="iconStyle"></u-icon>
</view>
<view class="u-alert-content" @tap.stop="click">
<view class="u-alert-title" :style="[uTitleStyle]">
{{title}}
</view>
<view v-if="description" class="u-alert-desc" :style="[descStyle]">
{{description}}
</view>
</view>
<view class="u-icon-wrap">
<u-icon @click="close" v-if="closeAble && !closeText" hoverClass="u-type-error-hover-color" name="close" color="#c0c4cc"
:size="22" class="u-close-icon" :style="{
top: description ? '18rpx' : '24rpx'
}"></u-icon>
</view>
<text v-if="closeAble && closeText" class="u-close-text" :style="{
top: description ? '18rpx' : '24rpx'
}">{{closeText}}</text>
</view>
</template>
<script>
/**
* alertTips 警告提示
* @description 警告提示,展现需要关注的信息
* @tutorial https://uviewui.com/components/alertTips.html
* @property {String} title 显示的标题文字
* @property {String} description 辅助性文字,颜色比title浅一点,字号也小一点,可选
* @property {String} type 关闭按钮(默认为叉号icon图标)
* @property {String} icon 图标名称
* @property {Object} icon-style 图标的样式,对象形式
* @property {Object} title-style 标题的样式,对象形式
* @property {Object} desc-style 描述的样式,对象形式
* @property {String} close-able 用文字替代关闭图标,close-able为true时有效
* @property {Boolean} show-icon 是否显示左边的辅助图标
* @property {Boolean} show 显示或隐藏组件
* @event {Function} click 点击组件时触发
* @event {Function} close 点击关闭按钮时触发
*/
export default {
name: 'u-alert-tips',
props: {
// 显示文字
title: {
type: String,
default: ''
},
// 主题,success/warning/info/error
type: {
type: String,
default: 'warning'
},
// 辅助性文字
description: {
type: String,
default: ''
},
// 是否可关闭
closeAble: {
type: Boolean,
default: false
},
// 关闭按钮自定义文本
closeText: {
type: String,
default: ''
},
// 是否显示图标
showIcon: {
type: Boolean,
default: false
},
// 文字颜色,如果定义了color值,icon会失效
color: {
type: String,
default: ''
},
// 背景颜色
bgColor: {
type: String,
default: ''
},
// 边框颜色
borderColor: {
type: String,
default: ''
},
// 是否显示
show: {
type: Boolean,
default: true
},
// 左边显示的icon
icon: {
type: String,
default: ''
},
// icon的样式
iconStyle: {
type: Object,
default() {
return {}
}
},
// 标题的样式
titleStyle: {
type: Object,
default() {
return {}
}
},
// 描述文字的样式
descStyle: {
type: Object,
default() {
return {}
}
},
},
data() {
return {
}
},
computed: {
uTitleStyle() {
let style = {};
// 如果有描述文字的话,标题进行加粗
style.fontWeight = this.description ? 500 : 'normal';
// 将用户传入样式对象和style合并,传入的优先级比style高,同属性会被覆盖
return this.$u.deepMerge(style, this.titleStyle);
},
uIcon() {
// 如果有设置icon名称就使用,否则根据type主题,推定一个默认的图标
return this.icon ? this.icon : this.$u.type2icon(this.type);
},
uIconType() {
// 如果有设置图标的样式,优先使用,没有的话,则用type的样式
return Object.keys(this.iconStyle).length ? '' : this.type;
}
},
methods: {
// 点击内容
click() {
this.$emit('click');
},
// 点击关闭按钮
close() {
this.$emit('close');
}
}
}
</script>
<style lang="scss" scoped>
@import "../../libs/css/style.components.scss";
.u-alert-tips {
@include vue-flex;
align-items: center;
padding: 16rpx 30rpx;
border-radius: 8rpx;
position: relative;
transition: all 0.3s linear;
border: 1px solid #fff;
&--bg--primary-light {
background-color: $u-type-primary-light;
}
&--bg--info-light {
background-color: $u-type-info-light;
}
&--bg--success-light {
background-color: $u-type-success-light;
}
&--bg--warning-light {
background-color: $u-type-warning-light;
}
&--bg--error-light {
background-color: $u-type-error-light;
}
&--border--primary-disabled {
border-color: $u-type-primary-disabled;
}
&--border--success-disabled {
border-color: $u-type-success-disabled;
}
&--border--error-disabled {
border-color: $u-type-error-disabled;
}
&--border--warning-disabled {
border-color: $u-type-warning-disabled;
}
&--border--info-disabled {
border-color: $u-type-info-disabled;
}
}
.u-close-alert-tips {
opacity: 0;
visibility: hidden;
}
.u-icon {
margin-right: 16rpx;
}
.u-alert-title {
font-size: 28rpx;
color: $u-main-color;
}
.u-alert-desc {
font-size: 26rpx;
text-align: left;
color: $u-content-color;
}
.u-close-icon {
position: absolute;
top: 20rpx;
right: 20rpx;
}
.u-close-hover {
color: red;
}
.u-close-text {
font-size: 24rpx;
color: $u-tips-color;
position: absolute;
top: 20rpx;
right: 20rpx;
line-height: 1;
}
</style>
<template>
<view class="content">
<view class="cropper-wrapper" :style="{ height: cropperOpt.height + 'px' }">
<canvas
class="cropper"
:disable-scroll="true"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
:style="{ width: cropperOpt.width, height: cropperOpt.height, backgroundColor: 'rgba(0, 0, 0, 0.8)' }"
canvas-id="cropper"
id="cropper"
></canvas>
<canvas
class="cropper"
:disable-scroll="true"
:style="{
position: 'fixed',
top: `-${cropperOpt.width * cropperOpt.pixelRatio}px`,
left: `-${cropperOpt.height * cropperOpt.pixelRatio}px`,
width: `${cropperOpt.width * cropperOpt.pixelRatio}px`,
height: `${cropperOpt.height * cropperOpt.pixelRatio}`
}"
canvas-id="targetId"
id="targetId"
></canvas>
</view>
<view class="cropper-buttons safe-area-padding" :style="{ height: bottomNavHeight + 'px' }">
<!-- #ifdef H5 -->
<view class="upload" @tap="uploadTap">选择图片</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<view class="upload" @tap="uploadTap">重新选择</view>
<!-- #endif -->
<view class="getCropperImage" @tap="getCropperImage(false)">确定</view>
</view>
</view>
</template>
<script>
import WeCropper from './weCropper.js';
export default {
props: {
// 裁剪矩形框的样式,其中可包含的属性为lineWidth-边框宽度(单位rpx),color: 边框颜色,
// mask-遮罩颜色,一般设置为一个rgba的透明度,如"rgba(0, 0, 0, 0.35)"
boundStyle: {
type: Object,
default() {
return {
lineWidth: 4,
borderColor: 'rgb(245, 245, 245)',
mask: 'rgba(0, 0, 0, 0.35)'
};
}
}
// // 裁剪框宽度,单位rpx
// rectWidth: {
// type: [String, Number],
// default: 400
// },
// // 裁剪框高度,单位rpx
// rectHeight: {
// type: [String, Number],
// default: 400
// },
// // 输出图片宽度,单位rpx
// destWidth: {
// type: [String, Number],
// default: 400
// },
// // 输出图片高度,单位rpx
// destHeight: {
// type: [String, Number],
// default: 400
// },
// // 输出的图片类型,如果发现裁剪的图片很大,可能是因为设置为了"png",改成"jpg"即可
// fileType: {
// type: String,
// default: 'jpg',
// },
// // 生成的图片质量
// // H5上无效,目前不考虑使用此参数
// quality: {
// type: [Number, String],
// default: 1
// }
},
data() {
return {
// 底部导航的高度
bottomNavHeight: 50,
originWidth: 200,
width: 0,
height: 0,
cropperOpt: {
id: 'cropper',
targetId: 'targetCropper',
pixelRatio: 1,
width: 0,
height: 0,
scale: 2.5,
zoom: 8,
cut: {
x: (this.width - this.originWidth) / 2,
y: (this.height - this.originWidth) / 2,
width: this.originWidth,
height: this.originWidth
},
boundStyle: {
lineWidth: uni.upx2px(this.boundStyle.lineWidth),
mask: this.boundStyle.mask,
color: this.boundStyle.borderColor
}
},
// 裁剪框和输出图片的尺寸,高度默认等于宽度
// 输出图片宽度,单位px
destWidth: 200,
// 裁剪框宽度,单位px
rectWidth: 200,
// 输出的图片类型,如果'png'类型发现裁剪的图片太大,改成"jpg"即可
fileType: 'jpg',
src: '', // 选择的图片路径,用于在点击确定时,判断是否选择了图片
};
},
onLoad(option) {
let rectInfo = uni.getSystemInfoSync();
this.width = rectInfo.windowWidth;
this.height = rectInfo.windowHeight - this.bottomNavHeight;
this.cropperOpt.width = this.width;
this.cropperOpt.height = this.height;
this.cropperOpt.pixelRatio = rectInfo.pixelRatio;
if (option.destWidth) this.destWidth = option.destWidth;
if (option.rectWidth) {
let rectWidth = Number(option.rectWidth);
this.cropperOpt.cut = {
x: (this.width - rectWidth) / 2,
y: (this.height - rectWidth) / 2,
width: rectWidth,
height: rectWidth
};
}
this.rectWidth = option.rectWidth;
if (option.fileType) this.fileType = option.fileType;
// 初始化
this.cropper = new WeCropper(this.cropperOpt)
.on('ready', ctx => {
// wecropper is ready for work!
})
.on('beforeImageLoad', ctx => {
// before picture loaded, i can do something
})
.on('imageLoad', ctx => {
// picture loaded
})
.on('beforeDraw', (ctx, instance) => {
// before canvas draw,i can do something
});
// 设置导航栏样式,以免用户在page.json中没有设置为黑色背景
uni.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: '#000000'
});
uni.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: res => {
this.src = res.tempFilePaths[0];
// 获取裁剪图片资源后,给data添加src属性及其值
this.cropper.pushOrign(this.src);
}
});
},
methods: {
touchStart(e) {
this.cropper.touchStart(e);
},
touchMove(e) {
this.cropper.touchMove(e);
},
touchEnd(e) {
this.cropper.touchEnd(e);
},
getCropperImage(isPre = false) {
if(!this.src) return this.$u.toast('请先选择图片再裁剪');
let cropper_opt = {
destHeight: Number(this.destWidth), // uni.canvasToTempFilePath要求这些参数为数值
destWidth: Number(this.destWidth),
fileType: this.fileType
};
this.cropper.getCropperImage(cropper_opt, (path, err) => {
if (err) {
uni.showModal({
title: '温馨提示',
content: err.message
});
} else {
if (isPre) {
uni.previewImage({
current: '', // 当前显示图片的 http 链接
urls: [path] // 需要预览的图片 http 链接列表
});
} else {
uni.$emit('uAvatarCropper', path);
this.$u.route({
type: 'back'
});
}
}
});
},
uploadTap() {
const self = this;
uni.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
self.src = res.tempFilePaths[0];
// 获取裁剪图片资源后,给data添加src属性及其值
self.cropper.pushOrign(this.src);
}
});
}
}
};
</script>
<style scoped lang="scss">
@import '../../libs/css/style.components.scss';
.content {
background: rgba(255, 255, 255, 1);
}
.cropper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 11;
}
.cropper-buttons {
background-color: #000000;
color: #eee;
}
.cropper-wrapper {
position: relative;
@include vue-flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
background-color: #000;
}
.cropper-buttons {
width: 100vw;
@include vue-flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
position: fixed;
bottom: 0;
left: 0;
font-size: 28rpx;
}
.cropper-buttons .upload,
.cropper-buttons .getCropperImage {
width: 50%;
text-align: center;
}
.cropper-buttons .upload {
text-align: left;
padding-left: 50rpx;
}
.cropper-buttons .getCropperImage {
text-align: right;
padding-right: 50rpx;
}
</style>
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!