Commit 55786551 by Jaxon

feat: 新增 uniapp demo项目

1 parent 4c34ae77
Showing 211 changed files with 17471 additions and 0 deletions
---
name: Bug report(报告问题)
about: Create a report to help us improve
---
<!--
注意:为更好的解决你的问题,请参考模板提供完整信息,准确描述问题,信息不全的 issue 将被关闭。
Note: In order to better solve your problem, please refer to the template to provide complete information, accurately describe the problem, and the incomplete information issue will be closed.
-->
# Bug report(问题描述)
please write your issue description here
## Steps to reproduce(问题复现步骤)
<!--
1. [xxx]
2. [xxx]
3. [xxxx]
-->
## Screenshot or Gif(截图或动态图)
## minimal reproduction(最小可还原代码)
## System Info
`npx envinfo --system --npmPackages vue --binaries --browsers`
执行上面命令,将结果贴下面
---
name: Feature Request(新功能建议)
about: Suggest an idea for this project
---
# Feature request(新功能建议)
name: Deploy Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ['main']
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
jobs:
# Build job
build:
runs-on: ubuntu-latest
steps:
# 设置服务器时区为东八区
- name: Set time zone
run: sudo timedatectl set-timezone 'Asia/Shanghai'
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8
- uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'pnpm'
- name: Install dependencies
run: pnpm i --no-frozen-lockfile
- name: Build
run: pnpm build:h5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./dist/build/h5
# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
node_modules*
.DS_Store
dist
*.local
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.hbuilderx
.stylelintcache
# rollup-plugin-visualizer 生成的分析文件
stats.html
# unplugin-auto-import 生成的类型文件
# auto-import.d.ts
# unplugin-vue-components 生成的类型文件
# components.d.ts
# vite-plugin-uni-pages 生成的类型文件
# uni-pages.d.ts
# 插件生成的文件
# src/pages.json
# src/manifest.json
# lock 文件还是不要了,我主要的版本写死就好了
# github actions 需要这些文件,所以main分支需要留着
# pnpm-lock.yaml
# package-lock.json
# TIPS:如果某些文件已经加入了版本管理,现在重新加入 .gitignore 是不生效的,需要执行下面的操作
# `git rm -r --cached .` 然后提交 commit 即可。
# git rm -r --cached file1 file2 ## 针对某些文件
# git rm -r --cached dir1 dir2 ## 针对某些文件夹
# git rm -r --cached . ## 针对所有文件
# 要跳过检查时,使用 --no-verify 过滤
# git commit -m 'feat: 引入 ucharts' --no-verify
# npx @dcloudio/uvm@latest 更新 uniapp
# registry = https://registry.npmjs.org
registry = https://registry.npmmirror.com
strict-peer-dependencies=false
auto-install-peers=true
shamefully-hoist=true
MIT License
Copyright (c) 2024 菲鸽
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">
<a href="https://github.com/feige996/unibest">
<img width="160" src="./src/static/logo.svg">
</a>
</p>
<h1 align="center">
<a href="https://github.com/feige996/unibest" target="_blank">unibest - 最好的 uniapp 开发框架</a>
</h1>
<div align="center">
旧仓库 codercup 进不去了,star 也拿不回来,这里也展示一下那个地址的 star.
[![GitHub Repo stars](https://img.shields.io/github/stars/codercup/unibest?style=flat&logo=github)](https://github.com/codercup/unibest)
[![GitHub forks](https://img.shields.io/github/forks/codercup/unibest?style=flat&logo=github)](https://github.com/codercup/unibest)
</div>
<div align="center">
[![GitHub Repo stars](https://img.shields.io/github/stars/feige996/unibest?style=flat&logo=github)](https://github.com/feige996/unibest)
[![GitHub forks](https://img.shields.io/github/forks/feige996/unibest?style=flat&logo=github)](https://github.com/feige996/unibest)
[![star](https://gitee.com/feige996/unibest/badge/star.svg?theme=dark)](https://gitee.com/feige996/unibest/stargazers)
[![fork](https://gitee.com/feige996/unibest/badge/fork.svg?theme=dark)](https://gitee.com/feige996/unibest/members)
![node version](https://img.shields.io/badge/node-%3E%3D18-green)
![pnpm version](https://img.shields.io/badge/pnpm-%3E%3D7.30-green)
![GitHub package.json version (subfolder of monorepo)](https://img.shields.io/github/package-json/v/feige996/unibest)
![GitHub License](https://img.shields.io/github/license/feige996/unibest)
</div>
`unibest` —— 最好的 `uniapp` 开发模板,由 `uniapp` + `Vue3` + `Ts` + `Vite5` + `UnoCss` + `wot-ui` + `z-paging` 构成,使用了最新的前端技术栈,无需依靠 `HBuilderX`,通过命令行方式运行 `web`、`小程序` 和 `App`(编辑器推荐 `VSCode`,可选 `webstorm`)。
`unibest` 内置了 `约定式路由`、`layout布局`、`请求封装`、`请求拦截`、`登录拦截`、`UnoCSS`、`i18n多语言` 等基础功能,提供了 `代码提示`、`自动格式化`、`统一配置`、`代码片段` 等辅助功能,让你编写 `uniapp` 拥有 `best` 体验 ( `unibest 的由来`)。
![](https://raw.githubusercontent.com/andreasbm/readme/master/screenshots/lines/rainbow.png)
<p align="center">
<a href="https://unibest.tech/" target="_blank">📖 文档地址</a>
<span style="margin:0 10px;">|</span>
<a href="https://feige996.github.io/hello-unibest/" target="_blank">📱 DEMO 地址</a>
</p>
---
注意旧的地址 [codercup](https://github.com/codercup/unibest) 我进不去了,使用新的 [feige996](https://github.com/feige996/unibest)。PR和 issue 也请使用新地址,否则无法合并。
## ⚙️ 环境
- node>=18
- pnpm>=7.30
- Vue Official>=2.1.10
- TypeScript>=5.0
## &#x1F4C2; 快速开始
执行 `pnpm create unibest` 创建项目
执行 `pnpm i` 安装依赖
执行 `pnpm dev` 运行 `H5`
## 📦 运行(支持热更新)
- web平台: `pnpm dev:h5`, 然后打开 [http://localhost:9000/](http://localhost:9000/)。
- weixin平台:`pnpm dev:mp-weixin` 然后打开微信开发者工具,导入本地文件夹,选择本项目的`dist/dev/mp-weixin` 文件。
- APP平台:`pnpm dev:app`, 然后打开 `HBuilderX`,导入刚刚生成的`dist/dev/app` 文件夹,选择运行到模拟器(开发时优先使用),或者运行的安卓/ios基座。
## 🔗 发布
- web平台: `pnpm build:h5`,打包后的文件在 `dist/build/h5`,可以放到web服务器,如nginx运行。如果最终不是放在根目录,可以在 `manifest.config.ts` 文件的 `h5.router.base` 属性进行修改。
- weixin平台:`pnpm build:mp-weixin`, 打包后的文件在 `dist/build/mp-weixin`,然后通过微信开发者工具导入,并点击右上角的“上传”按钮进行上传。
- APP平台:`pnpm build:app`, 然后打开 `HBuilderX`,导入刚刚生成的`dist/build/app` 文件夹,选择发行 - APP云打包。
## 📄 License
[MIT](https://opensource.org/license/mit/)
Copyright (c) 2024 菲鸽
## 捐赠
<p align='center'>
<img alt="special sponsor appwrite" src="./screenshots/pay-1.png" height="330" style="display:inline-block; height:330px;">
<img alt="special sponsor appwrite" src="./screenshots/pay-2.png" height="330" style="display:inline-block; height:330px; margin-left:10px;">
</p>
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by vite-plugin-uni-components
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {
export interface GlobalComponents {
AppTest: typeof import('./src/components/AppTest.vue')['default']
AppTest2: typeof import('./src/components/app-test-dir/AppTest2.vue')['default']
FlyContent: typeof import('./src/components/fly-content/fly-content.vue')['default']
FlyHeader: typeof import('./src/components/fly-header/fly-header.vue')['default']
FlyLogin: typeof import('./src/components/fly-login/fly-login.vue')['default']
FlyNavbar: typeof import('./src/components/fly-navbar/fly-navbar.vue')['default']
SvgIcon: typeof import('./src/components/SvgIcon.vue')['default']
}
}
VITE_APP_TITLE = 'unibest'
VITE_APP_PORT = 9000
# github actions 部署地址根路径,用在 manifest.config.ts 里面的 h5.router.base
VITE_APP_PUBLIC_BASE=/hello-unibest/
# TODO: 记得修改
VITE_UNI_APPID = 'H5871D791'
VITE_WX_APPID = 'wxa2abb91f64032a2b'
# fallback lacale:en, zh-Hans, zh-Hant 等
# 必须要在 lacale 文件夹中配置对应的 json 文件!!!
# 参考文档如下
# https://uniapp.dcloud.net.cn/tutorial/i18n.html
# https://uniapp.dcloud.net.cn/api/ui/locale.html#onlocalechange 打开页面后最下面的注意事项
VITE_FALLBACK_LOCALE = 'zh-Hans'
VITE_SERVER_BASEURL = 'https://ukw0y1.laf.run'
VITE_UPLOAD_BASEURL = 'https://ukw0y1.laf.run/upload'
VITE_ENV_FILE = '.env'
# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'development'
# 是否去除console 和 debugger
VITE_DELETE_CONSOLE = false
# VITE_SERVER_BASEURL = 'https://ukw0y1.laf.run'
VITE_ENV_FILE = '.env.development'
# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'development'
# 是否去除console 和 debugger
VITE_DELETE_CONSOLE = true
# VITE_SERVER_BASEURL = 'https://xxx.com'
VITE_ENV_FILE = '.env.production'
# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'development'
# 是否去除console 和 debugger
VITE_DELETE_CONSOLE = false
# VITE_SERVER_BASEURL = 'https://xxx.com'
VITE_ENV_FILE = '.env.test'
No preview for this file type
<!doctype html>
<html build-date="%BUILD_DATE%">
<head>
<meta charset="UTF-8" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<script>
var coverSupport =
'CSS' in window &&
typeof CSS.supports === 'function' &&
(CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') +
'" />',
)
</script>
<title>unibest</title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
// manifest.config.ts
import { defineManifestConfig } from '@uni-helper/vite-plugin-uni-manifest'
import path from 'node:path'
import { loadEnv } from 'vite'
// 获取环境变量的范例
const env = loadEnv(process.env.NODE_ENV!, path.resolve(process.cwd(), 'env'))
// console.log('manifest.config.ts')
// console.log(env)
const {
VITE_APP_TITLE,
VITE_UNI_APPID,
VITE_WX_APPID,
VITE_APP_PUBLIC_BASE,
VITE_FALLBACK_LOCALE,
} = env
export default defineManifestConfig({
name: VITE_APP_TITLE,
appid: VITE_UNI_APPID,
description: '',
versionName: '1.0.0',
versionCode: '100',
transformPx: false,
locale: VITE_FALLBACK_LOCALE, // 'zh-Hans'
h5: {
router: {
base: VITE_APP_PUBLIC_BASE,
},
},
/* 5+App特有相关 */
'app-plus': {
usingComponents: true,
nvueStyleCompiler: 'uni-app',
compilerVersion: 3,
splashscreen: {
alwaysShowBeforeRender: true,
waiting: true,
autoclose: true,
delay: 0,
},
/* 模块配置 */
modules: {},
/* 应用发布信息 */
distribute: {
/* android打包配置 */
android: {
minSdkVersion: 30,
targetSdkVersion: 30,
abiFilters: ['armeabi-v7a', 'arm64-v8a'],
permissions: [
'<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>',
'<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>',
'<uses-permission android:name="android.permission.VIBRATE"/>',
'<uses-permission android:name="android.permission.READ_LOGS"/>',
'<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>',
'<uses-feature android:name="android.hardware.camera.autofocus"/>',
'<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>',
'<uses-permission android:name="android.permission.CAMERA"/>',
'<uses-permission android:name="android.permission.GET_ACCOUNTS"/>',
'<uses-permission android:name="android.permission.READ_PHONE_STATE"/>',
'<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>',
'<uses-permission android:name="android.permission.WAKE_LOCK"/>',
'<uses-permission android:name="android.permission.FLASHLIGHT"/>',
'<uses-feature android:name="android.hardware.camera"/>',
'<uses-permission android:name="android.permission.WRITE_SETTINGS"/>',
],
},
/* ios打包配置 */
ios: {},
/* SDK配置 */
sdkConfigs: {},
/* 图标配置 */
icons: {
android: {},
ios: {},
},
},
},
/* 快应用特有相关 */
quickapp: {},
/* 小程序特有相关 */
'mp-weixin': {
appid: VITE_WX_APPID,
setting: {
urlCheck: false,
},
usingComponents: true,
// __usePrivacyCheck__: true,
},
'mp-alipay': {
usingComponents: true,
},
'mp-baidu': {
usingComponents: true,
},
'mp-toutiao': {
usingComponents: true,
},
uniStatistics: {
enable: false,
},
vueVersion: '3',
})
import { createProdMockServer } from 'vite-plugin-mock/client'
const modules = import.meta.glob('/mock/**/*.ts', { eager: true })
const mockModules: any[] = []
Object.keys(modules).forEach((key) => {
if (key.includes('/_')) {
return
}
mockModules.push(...(modules as Recordable)[key].default)
})
console.log('mockModules -> ', mockModules)
/**
* Used in a production environment. Need to manually import all modules
*/
export function setupProdMockServer() {
createProdMockServer(mockModules)
}
// test.ts
import { MockMethod, MockConfig } from 'vite-plugin-mock'
export default [
{
url: '/api/get',
method: 'get',
response: ({ query }) => {
return {
code: 0,
data: {
name: '菲鸽',
},
}
},
},
{
url: '/api/post',
method: 'post',
timeout: 2000,
response: {
code: 0,
data: {
name: '菲鸽',
},
},
},
{
url: '/api/text',
method: 'post',
rawResponse: async (req, res) => {
let reqbody = ''
await new Promise((resolve) => {
req.on('data', (chunk) => {
reqbody += chunk
})
req.on('end', () => resolve(undefined))
})
res.setHeader('Content-Type', 'text/plain')
res.statusCode = 200
res.end(`hello, ${reqbody}`)
},
},
] as MockMethod[]
{
"name": "unibest",
"type": "commonjs",
"version": "1.5.0",
"description": "unibest - 最好的 uniapp 开发模板",
"author": {
"name": "feige996",
"zhName": "菲鸽",
"email": "1020103647@qq.com",
"github": "https://github.com/feige996",
"gitee": "https://gitee.com/feige996"
},
"license": "MIT",
"repository": "https://github.com/feige996/unibest",
"repository-gitee": "https://gitee.com/feige996/unibest",
"bugs": {
"url": "https://github.com/feige996/unibest/issues"
},
"homepage": "https://feige996.github.io/hello-unibest/",
"engines": {
"node": ">=18",
"pnpm": ">=7.30"
},
"scripts": {
"dev:app": "uni -p app",
"dev:app-android": "uni -p app-android",
"dev:app-ios": "uni -p app-ios",
"dev:custom": "uni -p",
"dev": "uni",
"dev-dev": "uni --mode development",
"dev-test": "uni --mode test",
"dev-prod": "uni --mode production",
"dev:h5": "uni",
"dev:h5:ssr": "uni --ssr",
"dev:mp": "uni -p mp-weixin",
"dev:mp-alipay": "uni -p mp-alipay",
"dev:mp-baidu": "uni -p mp-baidu",
"dev:mp-jd": "uni -p mp-jd",
"dev:mp-kuaishou": "uni -p mp-kuaishou",
"dev:mp-lark": "uni -p mp-lark",
"dev:mp-qq": "uni -p mp-qq",
"dev:mp-toutiao": "uni -p mp-toutiao",
"dev:mp-weixin": "uni -p mp-weixin",
"dev:quickapp-webview": "uni -p quickapp-webview",
"dev:quickapp-webview-huawei": "uni -p quickapp-webview-huawei",
"dev:quickapp-webview-union": "uni -p quickapp-webview-union",
"build:app": "uni build -p app",
"build:app-android": "uni build -p app-android",
"build:app-ios": "uni build -p app-ios",
"build:custom": "uni build -p",
"build:h5": "uni build",
"build": "uni build",
"build:h5:ssr": "uni build --ssr",
"build:mp-alipay": "uni build -p mp-alipay",
"build:mp": "uni build -p mp-weixin",
"build:mp-baidu": "uni build -p mp-baidu",
"build:mp-jd": "uni build -p mp-jd",
"build:mp-kuaishou": "uni build -p mp-kuaishou",
"build:mp-lark": "uni build -p mp-lark",
"build:mp-qq": "uni build -p mp-qq",
"build:mp-toutiao": "uni build -p mp-toutiao",
"build:mp-weixin": "uni build -p mp-weixin",
"build:quickapp-webview": "uni build -p quickapp-webview",
"build:quickapp-webview-huawei": "uni build -p quickapp-webview-huawei",
"build:quickapp-webview-union": "uni build -p quickapp-webview-union",
"prepare": "node ./shell/postinstall.js & git init && husky install ",
"type-check": "vue-tsc --noEmit"
},
"lint-staged": {
"**/*.{html,vue,ts,cjs,json,md}": [
"prettier --write"
],
"**/*.{vue,js,ts,jsx,tsx}": [
"eslint --fix"
],
"**/*.{vue,css,scss,html}": [
"stylelint --fix --allow-empty-input"
]
},
"resolutions": {
"bin-wrapper": "npm:bin-wrapper-china"
},
"dependencies": {
"@climblee/uv-ui": "^1.1.20",
"@dcloudio/uni-app": "3.0.0-4000820240401001",
"@dcloudio/uni-app-plus": "3.0.0-4000820240401001",
"@dcloudio/uni-components": "3.0.0-4000820240401001",
"@dcloudio/uni-h5": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-alipay": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-baidu": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-jd": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-kuaishou": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-lark": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-qq": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-toutiao": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-weixin": "3.0.0-4000820240401001",
"@dcloudio/uni-mp-xhs": "3.0.0-4000820240401001",
"@dcloudio/uni-quickapp-webview": "3.0.0-4000820240401001",
"@dcloudio/uni-ui": "1.5.0",
"dayjs": "1.11.10",
"echarts": "^5.6.0",
"lodash-es": "^4.17.21",
"pinia": "2.0.36",
"pinia-plugin-persistedstate": "3.2.1",
"qs": "6.5.3",
"vue": "3.3.11",
"vue-i18n": "^9.10.2",
"wot-design-uni": "^1.9.1",
"z-paging": "^2.7.8"
},
"devDependencies": {
"@commitlint/cli": "^18.4.3",
"@commitlint/config-conventional": "^18.4.3",
"@dcloudio/types": "^3.4.8",
"@dcloudio/uni-automator": "3.0.0-4000820240401001",
"@dcloudio/uni-cli-shared": "3.0.0-4000820240401001",
"@dcloudio/uni-stacktracey": "3.0.0-4000820240401001",
"@dcloudio/vite-plugin-uni": "3.0.0-4000820240401001",
"@iconify-json/carbon": "^1.1.27",
"@ttou/uv-typings": "^1.10.2",
"@types/node": "^20.11.5",
"@types/wechat-miniprogram": "^3.4.7",
"@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^6.15.0",
"@uni-helper/uni-ui-types": "^0.5.11",
"@uni-helper/vite-plugin-uni-components": "^0.0.8",
"@uni-helper/vite-plugin-uni-layouts": "^0.1.7",
"@uni-helper/vite-plugin-uni-manifest": "^0.2.3",
"@uni-helper/vite-plugin-uni-pages": "^0.2.15",
"@uni-helper/vite-plugin-uni-platform": "^0.0.4",
"@unocss/preset-legacy-compat": "0.58.9",
"@vue/runtime-core": "^3.3.13",
"@vue/tsconfig": "^0.1.3",
"autoprefixer": "^10.4.16",
"commitlint": "^18.4.3",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard": "^17.1.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.0",
"eslint-plugin-vue": "^9.19.2",
"husky": "^8.0.3",
"lint-staged": "^15.2.0",
"postcss": "^8.4.32",
"postcss-html": "^1.5.0",
"postcss-scss": "^4.0.9",
"rollup-plugin-visualizer": "^5.11.0",
"sass": "1.77.8",
"stylelint": "^16.0.2",
"stylelint-config-html": "^1.1.0",
"stylelint-config-recess-order": "^4.4.0",
"stylelint-config-recommended-vue": "^1.5.0",
"stylelint-config-standard": "^35.0.0",
"stylelint-config-standard-scss": "^12.0.0",
"stylelint-prettier": "^5.0.0",
"terser": "^5.26.0",
"typescript": "^4.9.4",
"unocss": "^0.58.9",
"unocss-applet": "^0.7.8",
"unplugin-auto-import": "^0.17.2",
"vite": "4.3.5",
"vite-plugin-imagemin": "^0.6.1",
"vite-plugin-mock": "^3.0.1",
"vite-plugin-restart": "^0.4.0",
"vite-plugin-svg-icons": "^2.0.1",
"vite-plugin-vue-setup-extend": "^0.4.0",
"vite-svg-loader": "^5.1.0",
"vue-tsc": "^1.8.25"
}
}
import { defineUniPages } from '@uni-helper/vite-plugin-uni-pages'
export default defineUniPages({
globalStyle: {
navigationStyle: 'default',
navigationBarTitleText: 'unibest',
navigationBarBackgroundColor: '#f8f8f8',
navigationBarTextStyle: 'black',
backgroundColor: '#FFFFFF',
h5: {
// navigationStyle: 'custom',
},
},
easycom: {
autoscan: true,
custom: {
'^uni-(.*)': '@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue',
'^uv-(.*)': '@climblee/uv-ui/components/uv-$1/uv-$1.vue',
'^wd-(.*)': 'wot-design-uni/components/wd-$1/wd-$1.vue',
'^(?!z-paging-refresh|z-paging-load-more)z-paging(.*)':
'z-paging/components/z-paging$1/z-paging$1.vue',
},
},
tabBar: {
color: '#999999',
selectedColor: '#018d71',
backgroundColor: '#F8F8F8',
borderStyle: 'black',
height: '50px',
fontSize: '10px',
iconWidth: '24px',
spacing: '3px',
list: [
{
iconPath: 'static/tabbar/home.png',
selectedIconPath: 'static/tabbar/homeHL.png',
pagePath: 'pages/index/index',
text: '首页',
},
{
iconPath: 'static/tabbar/example.png',
selectedIconPath: 'static/tabbar/exampleHL.png',
pagePath: 'pages/demo/index',
text: '示例',
},
],
},
})
This diff could not be displayed because it is too large.
/**
* 本文件会在依赖包安装时执行,用以生成 `src/manifest.json`
* 如果不存在 `src/manifest.json` 会运行报错,提示找不到 `src/manifest.json`
* 如果中途自己删除了 'src/manifest.json' 文件,记得手动执行本文件,可以右键 `Run Code` 快速执行
*
* 本文件是为了兼容 window 系统才生成的
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs')
const filePath = './src/manifest.json'
if (fs.existsSync(filePath)) {
// console.log(`${filePath}存在`)
} else {
// console.log(`${filePath}不存在,需要创建`)
fs.writeFile(filePath, '{}\n', {}, () => {
// console.log(`${filePath}已经成功创建,并写入{}`)
})
}
# 本文件会在依赖包安装时执行,用以生成 `src/manifest.json`
# 如果不存在 `src/manifest.json` 会运行报错,提示找不到 `src/manifest.json`
# 如果中途自己删除了 'src/manifest.json' 文件,记得手动执行本文件,可以右键 `Run Code` 快速执行
if test -f ./src/manifest.json; then
echo ./src/manifest.json 存在
else
touch ./src/manifest.json
echo "{}" >./src/manifest.json
fi
# pnpm build:app 之后会生成 unpackage/dist/build/app
# 我要把它改名为 unpackage/dist/build/unibest_app_build
# 只有存在新的 app 文件时,才执行这些操作!!否则会误删!!
if test -d ./dist/build/app; then
echo '存在新打包出来的app - build'
cd ./dist/build/
# 1、删除旧的 rename 后的文件夹
if test -d './unibest_app_build'; then
rm -rf ./unibest_app_build
fi
# 2、把 app 命名为 unibest_app_build
mv ./app ./unibest_app_build
fi
if test -d ./dist/dev/app; then
echo '存在新打包出来的app - dev'
cd ./dist/dev/
# 1、删除旧的 rename 后的文件夹
if test -d './unibest_app_dev'; then
rm -rf ./unibest_app_dev
fi
# 2、把 app 命名为 unibest_app_build
mv ./app ./unibest_app_dev
fi
/// <reference types='@dcloudio/types' />
import 'vue'
declare module '@vue/runtime-core' {
type Hooks = App.AppInstance & Page.PageInstance
interface ComponentCustomOptions extends Hooks {}
}
<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
onLaunch(() => {
console.log('App Launch')
})
onShow(() => {
console.log('App Show')
})
onHide(() => {
console.log('App Hide')
})
</script>
<style lang="scss">
/* stylelint-disable selector-type-no-unknown */
button::after {
border: none;
}
swiper,
scroll-view {
flex: 1;
height: 100%;
overflow: hidden;
}
image {
width: 100%;
height: 100%;
vertical-align: middle;
}
// 单行省略,优先使用 unocss: text-ellipsis
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
// 两行省略
.ellipsis-2 {
display: -webkit-box;
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
// 三行省略
.ellipsis-3 {
display: -webkit-box;
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
</style>
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1712309809495" class="icon" viewBox="0 0 1049 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4978" xmlns:xlink="http://www.w3.org/1999/xlink" width="65.5625" height="64"><path d="M161.4336 0h624.1024c107.6224 0 161.4336 53.6832 161.4336 161.0752v687.7696c0 107.392-53.8112 161.0752-161.4336 161.0752H161.4336C53.8112 1009.92 0 956.2368 0 848.8448V161.0752C0 53.6832 53.8112 0 161.4336 0z" fill="#01B26A" p-id="4979"></path><path d="M672.1792 352.1024H181.632c-26.88 0-48.64-21.7088-48.64-48.512 0-26.8288 21.76-48.5376 48.64-48.5376h490.5472c26.88 0 48.64 21.7088 48.64 48.5376 0 26.8032-21.76 48.512-48.64 48.512zM485.888 627.84H181.8624c-26.88 0-48.64-21.7344-48.64-48.5376s21.76-48.5376 48.64-48.5376H485.888c26.88 0 48.64 21.76 48.64 48.5376 0 26.8032-21.76 48.5376-48.64 48.5376z" fill="#FFFFFF" p-id="4980"></path><path d="M523.264 761.4208C523.264 906.4448 641.1264 1024 786.432 1024 931.7888 1024 1049.6 906.4448 1049.6 761.4208c0-144.9984-117.8112-262.5536-263.168-262.5536-145.3312 0-263.168 117.5552-263.168 262.5536z" fill="#28D493" fill-opacity=".517" p-id="4981"></path><path d="M786.432 498.944c-128.768-0.1792-238.72 92.6976-259.84 219.4432a262.4512 262.4512 0 0 0 174.72 291.5328h84.0448c89.088 0.1024 161.4336-71.8592 161.6128-160.768V553.5232a261.8368 261.8368 0 0 0-160.512-54.6048z" fill="#00AA69" p-id="4982"></path><path d="M724.0448 918.272a48.64 48.64 0 0 1-44.0832-28.1088 48.4352 48.4352 0 0 1 6.9376-51.7376l71.1936-84.0192v-115.8144c0-26.8032 21.7856-48.5376 48.64-48.5376 26.88 0 48.64 21.7344 48.64 48.5376v133.4528c0 11.4688-4.0704 22.5536-11.4688 31.3088l-82.688 97.6128c-9.216 10.9312-22.8352 17.28-37.1712 17.28z" fill="#FFFFFF" p-id="4983"></path></svg>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1712309809495" class="icon" viewBox="0 0 1049 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4978" xmlns:xlink="http://www.w3.org/1999/xlink" width="65.5625" height="64"><path d="M161.4336 0h624.1024c107.6224 0 161.4336 53.6832 161.4336 161.0752v687.7696c0 107.392-53.8112 161.0752-161.4336 161.0752H161.4336C53.8112 1009.92 0 956.2368 0 848.8448V161.0752C0 53.6832 53.8112 0 161.4336 0z" fill="#01B26A" p-id="4979"></path><path d="M672.1792 352.1024H181.632c-26.88 0-48.64-21.7088-48.64-48.512 0-26.8288 21.76-48.5376 48.64-48.5376h490.5472c26.88 0 48.64 21.7088 48.64 48.5376 0 26.8032-21.76 48.512-48.64 48.512zM485.888 627.84H181.8624c-26.88 0-48.64-21.7344-48.64-48.5376s21.76-48.5376 48.64-48.5376H485.888c26.88 0 48.64 21.76 48.64 48.5376 0 26.8032-21.76 48.5376-48.64 48.5376z" fill="#FFFFFF" p-id="4980"></path><path d="M523.264 761.4208C523.264 906.4448 641.1264 1024 786.432 1024 931.7888 1024 1049.6 906.4448 1049.6 761.4208c0-144.9984-117.8112-262.5536-263.168-262.5536-145.3312 0-263.168 117.5552-263.168 262.5536z" fill="#28D493" fill-opacity=".517" p-id="4981"></path><path d="M786.432 498.944c-128.768-0.1792-238.72 92.6976-259.84 219.4432a262.4512 262.4512 0 0 0 174.72 291.5328h84.0448c89.088 0.1024 161.4336-71.8592 161.6128-160.768V553.5232a261.8368 261.8368 0 0 0-160.512-54.6048z" fill="#00AA69" p-id="4982"></path><path d="M724.0448 918.272a48.64 48.64 0 0 1-44.0832-28.1088 48.4352 48.4352 0 0 1 6.9376-51.7376l71.1936-84.0192v-115.8144c0-26.8032 21.7856-48.5376 48.64-48.5376 26.88 0 48.64 21.7344 48.64 48.5376v133.4528c0 11.4688-4.0704 22.5536-11.4688 31.3088l-82.688 97.6128c-9.216 10.9312-22.8352 17.28-37.1712 17.28z" fill="#FFFFFF" p-id="4983"></path></svg>
\ No newline at end of file \ No newline at end of file
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
export {}
declare global {
const EffectScope: typeof import('vue')['EffectScope']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const effectScope: typeof import('vue')['effectScope']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const markRaw: typeof import('vue')['markRaw']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onAddToFavorites: typeof import('@dcloudio/uni-app')['onAddToFavorites']
const onBackPress: typeof import('@dcloudio/uni-app')['onBackPress']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onError: typeof import('@dcloudio/uni-app')['onError']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onHide: typeof import('@dcloudio/uni-app')['onHide']
const onLaunch: typeof import('@dcloudio/uni-app')['onLaunch']
const onLoad: typeof import('@dcloudio/uni-app')['onLoad']
const onMounted: typeof import('vue')['onMounted']
const onNavigationBarButtonTap: typeof import('@dcloudio/uni-app')['onNavigationBarButtonTap']
const onNavigationBarSearchInputChanged: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputChanged']
const onNavigationBarSearchInputClicked: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputClicked']
const onNavigationBarSearchInputConfirmed: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputConfirmed']
const onNavigationBarSearchInputFocusChanged: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputFocusChanged']
const onPageNotFound: typeof import('@dcloudio/uni-app')['onPageNotFound']
const onPageScroll: typeof import('@dcloudio/uni-app')['onPageScroll']
const onPullDownRefresh: typeof import('@dcloudio/uni-app')['onPullDownRefresh']
const onReachBottom: typeof import('@dcloudio/uni-app')['onReachBottom']
const onReady: typeof import('@dcloudio/uni-app')['onReady']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onResize: typeof import('@dcloudio/uni-app')['onResize']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onShareAppMessage: typeof import('@dcloudio/uni-app')['onShareAppMessage']
const onShareTimeline: typeof import('@dcloudio/uni-app')['onShareTimeline']
const onShow: typeof import('@dcloudio/uni-app')['onShow']
const onTabItemTap: typeof import('@dcloudio/uni-app')['onTabItemTap']
const onThemeChange: typeof import('@dcloudio/uni-app')['onThemeChange']
const onUnhandledRejection: typeof import('@dcloudio/uni-app')['onUnhandledRejection']
const onUnload: typeof import('@dcloudio/uni-app')['onUnload']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const provide: typeof import('vue')['provide']
const reactive: typeof import('vue')['reactive']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useNavbarWeixin: typeof import('./hooks/useNavbarWeixin')['default']
const useSlots: typeof import('vue')['useSlots']
const useUpload: typeof import('./hooks/useUpload')['default']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, ComponentPublicInstance, ComputedRef, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, VNode, WritableComputedRef } from 'vue'
import('vue')
}
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly EffectScope: UnwrapRef<typeof import('vue')['EffectScope']>
readonly computed: UnwrapRef<typeof import('vue')['computed']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
readonly defineAsyncComponent: UnwrapRef<typeof import('vue')['defineAsyncComponent']>
readonly defineComponent: UnwrapRef<typeof import('vue')['defineComponent']>
readonly effectScope: UnwrapRef<typeof import('vue')['effectScope']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
readonly isReadonly: UnwrapRef<typeof import('vue')['isReadonly']>
readonly isRef: UnwrapRef<typeof import('vue')['isRef']>
readonly markRaw: UnwrapRef<typeof import('vue')['markRaw']>
readonly nextTick: UnwrapRef<typeof import('vue')['nextTick']>
readonly onActivated: UnwrapRef<typeof import('vue')['onActivated']>
readonly onAddToFavorites: UnwrapRef<typeof import('@dcloudio/uni-app')['onAddToFavorites']>
readonly onBackPress: UnwrapRef<typeof import('@dcloudio/uni-app')['onBackPress']>
readonly onBeforeMount: UnwrapRef<typeof import('vue')['onBeforeMount']>
readonly onBeforeUnmount: UnwrapRef<typeof import('vue')['onBeforeUnmount']>
readonly onBeforeUpdate: UnwrapRef<typeof import('vue')['onBeforeUpdate']>
readonly onDeactivated: UnwrapRef<typeof import('vue')['onDeactivated']>
readonly onError: UnwrapRef<typeof import('@dcloudio/uni-app')['onError']>
readonly onErrorCaptured: UnwrapRef<typeof import('vue')['onErrorCaptured']>
readonly onHide: UnwrapRef<typeof import('@dcloudio/uni-app')['onHide']>
readonly onLaunch: UnwrapRef<typeof import('@dcloudio/uni-app')['onLaunch']>
readonly onLoad: UnwrapRef<typeof import('@dcloudio/uni-app')['onLoad']>
readonly onMounted: UnwrapRef<typeof import('vue')['onMounted']>
readonly onNavigationBarButtonTap: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarButtonTap']>
readonly onNavigationBarSearchInputChanged: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputChanged']>
readonly onNavigationBarSearchInputClicked: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputClicked']>
readonly onNavigationBarSearchInputConfirmed: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputConfirmed']>
readonly onNavigationBarSearchInputFocusChanged: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputFocusChanged']>
readonly onPageNotFound: UnwrapRef<typeof import('@dcloudio/uni-app')['onPageNotFound']>
readonly onPageScroll: UnwrapRef<typeof import('@dcloudio/uni-app')['onPageScroll']>
readonly onPullDownRefresh: UnwrapRef<typeof import('@dcloudio/uni-app')['onPullDownRefresh']>
readonly onReachBottom: UnwrapRef<typeof import('@dcloudio/uni-app')['onReachBottom']>
readonly onReady: UnwrapRef<typeof import('@dcloudio/uni-app')['onReady']>
readonly onRenderTracked: UnwrapRef<typeof import('vue')['onRenderTracked']>
readonly onRenderTriggered: UnwrapRef<typeof import('vue')['onRenderTriggered']>
readonly onResize: UnwrapRef<typeof import('@dcloudio/uni-app')['onResize']>
readonly onScopeDispose: UnwrapRef<typeof import('vue')['onScopeDispose']>
readonly onServerPrefetch: UnwrapRef<typeof import('vue')['onServerPrefetch']>
readonly onShareAppMessage: UnwrapRef<typeof import('@dcloudio/uni-app')['onShareAppMessage']>
readonly onShareTimeline: UnwrapRef<typeof import('@dcloudio/uni-app')['onShareTimeline']>
readonly onShow: UnwrapRef<typeof import('@dcloudio/uni-app')['onShow']>
readonly onTabItemTap: UnwrapRef<typeof import('@dcloudio/uni-app')['onTabItemTap']>
readonly onThemeChange: UnwrapRef<typeof import('@dcloudio/uni-app')['onThemeChange']>
readonly onUnhandledRejection: UnwrapRef<typeof import('@dcloudio/uni-app')['onUnhandledRejection']>
readonly onUnload: UnwrapRef<typeof import('@dcloudio/uni-app')['onUnload']>
readonly onUnmounted: UnwrapRef<typeof import('vue')['onUnmounted']>
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
readonly readonly: UnwrapRef<typeof import('vue')['readonly']>
readonly ref: UnwrapRef<typeof import('vue')['ref']>
readonly resolveComponent: UnwrapRef<typeof import('vue')['resolveComponent']>
readonly shallowReactive: UnwrapRef<typeof import('vue')['shallowReactive']>
readonly shallowReadonly: UnwrapRef<typeof import('vue')['shallowReadonly']>
readonly shallowRef: UnwrapRef<typeof import('vue')['shallowRef']>
readonly toRaw: UnwrapRef<typeof import('vue')['toRaw']>
readonly toRef: UnwrapRef<typeof import('vue')['toRef']>
readonly toRefs: UnwrapRef<typeof import('vue')['toRefs']>
readonly toValue: UnwrapRef<typeof import('vue')['toValue']>
readonly triggerRef: UnwrapRef<typeof import('vue')['triggerRef']>
readonly unref: UnwrapRef<typeof import('vue')['unref']>
readonly useAttrs: UnwrapRef<typeof import('vue')['useAttrs']>
readonly useCssModule: UnwrapRef<typeof import('vue')['useCssModule']>
readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
readonly useNavbarWeixin: UnwrapRef<typeof import('./hooks/useNavbarWeixin')['default']>
readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
readonly useUpload: UnwrapRef<typeof import('./hooks/useUpload')['default']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>
readonly watchPostEffect: UnwrapRef<typeof import('vue')['watchPostEffect']>
readonly watchSyncEffect: UnwrapRef<typeof import('vue')['watchSyncEffect']>
}
}
declare module '@vue/runtime-core' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly EffectScope: UnwrapRef<typeof import('vue')['EffectScope']>
readonly computed: UnwrapRef<typeof import('vue')['computed']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
readonly defineAsyncComponent: UnwrapRef<typeof import('vue')['defineAsyncComponent']>
readonly defineComponent: UnwrapRef<typeof import('vue')['defineComponent']>
readonly effectScope: UnwrapRef<typeof import('vue')['effectScope']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
readonly isReadonly: UnwrapRef<typeof import('vue')['isReadonly']>
readonly isRef: UnwrapRef<typeof import('vue')['isRef']>
readonly markRaw: UnwrapRef<typeof import('vue')['markRaw']>
readonly nextTick: UnwrapRef<typeof import('vue')['nextTick']>
readonly onActivated: UnwrapRef<typeof import('vue')['onActivated']>
readonly onAddToFavorites: UnwrapRef<typeof import('@dcloudio/uni-app')['onAddToFavorites']>
readonly onBackPress: UnwrapRef<typeof import('@dcloudio/uni-app')['onBackPress']>
readonly onBeforeMount: UnwrapRef<typeof import('vue')['onBeforeMount']>
readonly onBeforeUnmount: UnwrapRef<typeof import('vue')['onBeforeUnmount']>
readonly onBeforeUpdate: UnwrapRef<typeof import('vue')['onBeforeUpdate']>
readonly onDeactivated: UnwrapRef<typeof import('vue')['onDeactivated']>
readonly onError: UnwrapRef<typeof import('@dcloudio/uni-app')['onError']>
readonly onErrorCaptured: UnwrapRef<typeof import('vue')['onErrorCaptured']>
readonly onHide: UnwrapRef<typeof import('@dcloudio/uni-app')['onHide']>
readonly onLaunch: UnwrapRef<typeof import('@dcloudio/uni-app')['onLaunch']>
readonly onLoad: UnwrapRef<typeof import('@dcloudio/uni-app')['onLoad']>
readonly onMounted: UnwrapRef<typeof import('vue')['onMounted']>
readonly onNavigationBarButtonTap: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarButtonTap']>
readonly onNavigationBarSearchInputChanged: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputChanged']>
readonly onNavigationBarSearchInputClicked: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputClicked']>
readonly onNavigationBarSearchInputConfirmed: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputConfirmed']>
readonly onNavigationBarSearchInputFocusChanged: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputFocusChanged']>
readonly onPageNotFound: UnwrapRef<typeof import('@dcloudio/uni-app')['onPageNotFound']>
readonly onPageScroll: UnwrapRef<typeof import('@dcloudio/uni-app')['onPageScroll']>
readonly onPullDownRefresh: UnwrapRef<typeof import('@dcloudio/uni-app')['onPullDownRefresh']>
readonly onReachBottom: UnwrapRef<typeof import('@dcloudio/uni-app')['onReachBottom']>
readonly onReady: UnwrapRef<typeof import('@dcloudio/uni-app')['onReady']>
readonly onRenderTracked: UnwrapRef<typeof import('vue')['onRenderTracked']>
readonly onRenderTriggered: UnwrapRef<typeof import('vue')['onRenderTriggered']>
readonly onResize: UnwrapRef<typeof import('@dcloudio/uni-app')['onResize']>
readonly onScopeDispose: UnwrapRef<typeof import('vue')['onScopeDispose']>
readonly onServerPrefetch: UnwrapRef<typeof import('vue')['onServerPrefetch']>
readonly onShareAppMessage: UnwrapRef<typeof import('@dcloudio/uni-app')['onShareAppMessage']>
readonly onShareTimeline: UnwrapRef<typeof import('@dcloudio/uni-app')['onShareTimeline']>
readonly onShow: UnwrapRef<typeof import('@dcloudio/uni-app')['onShow']>
readonly onTabItemTap: UnwrapRef<typeof import('@dcloudio/uni-app')['onTabItemTap']>
readonly onThemeChange: UnwrapRef<typeof import('@dcloudio/uni-app')['onThemeChange']>
readonly onUnhandledRejection: UnwrapRef<typeof import('@dcloudio/uni-app')['onUnhandledRejection']>
readonly onUnload: UnwrapRef<typeof import('@dcloudio/uni-app')['onUnload']>
readonly onUnmounted: UnwrapRef<typeof import('vue')['onUnmounted']>
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
readonly readonly: UnwrapRef<typeof import('vue')['readonly']>
readonly ref: UnwrapRef<typeof import('vue')['ref']>
readonly resolveComponent: UnwrapRef<typeof import('vue')['resolveComponent']>
readonly shallowReactive: UnwrapRef<typeof import('vue')['shallowReactive']>
readonly shallowReadonly: UnwrapRef<typeof import('vue')['shallowReadonly']>
readonly shallowRef: UnwrapRef<typeof import('vue')['shallowRef']>
readonly toRaw: UnwrapRef<typeof import('vue')['toRaw']>
readonly toRef: UnwrapRef<typeof import('vue')['toRef']>
readonly toRefs: UnwrapRef<typeof import('vue')['toRefs']>
readonly toValue: UnwrapRef<typeof import('vue')['toValue']>
readonly triggerRef: UnwrapRef<typeof import('vue')['triggerRef']>
readonly unref: UnwrapRef<typeof import('vue')['unref']>
readonly useAttrs: UnwrapRef<typeof import('vue')['useAttrs']>
readonly useCssModule: UnwrapRef<typeof import('vue')['useCssModule']>
readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
readonly useNavbarWeixin: UnwrapRef<typeof import('./hooks/useNavbarWeixin')['default']>
readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
readonly useUpload: UnwrapRef<typeof import('./hooks/useUpload')['default']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>
readonly watchPostEffect: UnwrapRef<typeof import('vue')['watchPostEffect']>
readonly watchSyncEffect: UnwrapRef<typeof import('vue')['watchSyncEffect']>
}
}
<!-- 本文件会自动导入 -->
<template>
<view>
<view>components 里面的 AppTest.vue 组件</view>
<slot />
</view>
</template>
<template>
<svg aria-hidden="true">
<use :href="symbolId" :fill="color" />
</svg>
</template>
<script lang="ts" setup name="SvgIcon">
const props = withDefaults(
defineProps<{
prefix?: string
name: string
color?: string
}>(),
{
prefix: 'icon',
name: '',
color: '#333',
},
)
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
</script>
<template>
<view>
<view>components 里面的 app-test-dir/AppTest.vue 组件</view>
<slot />
</view>
</template>
<template>
<view class="fly-content">
<view v-for="n in line" :key="n" class="h-10 leading-10 text-center">
很多内容,这里是第{{ n }}行
</view>
</view>
</template>
<script lang="ts" setup>
withDefaults(defineProps<{ line?: number }>(), { line: 10 })
</script>
<template>
<view class="text-green-500">header</view>
</template>
# fly-login
点击“点击显示微信头像”按钮后,出现的半屏登录弹窗,可以在任意页面引入。
仿“掘金小册”小程序。
![掘金小册登录](screenshot.png)
<template>
<view class="fly-login" v-if="modelValue">
<view class="fly-login-mask" />
<view class="fly-login-content px-4">
<view class="font-bold h-16 leading-16">获取您的昵称、头像</view>
<view
class="rounded-full bg-light-600 w-6 h-6 text-center absolute top-4 right-4"
@click="onClose"
>
<view class="i-carbon-close text-gray-700" />
</view>
<view
class="flex items-center h-16 leading-16 border-b-gray-400 border-b-solid border-[1rpx]"
>
<text class="mr-4 flex-shrink-0">头像</text>
<button
class="bg-transparent flex items-center after:b-none w-full h-12 leading-12"
open-type="chooseAvatar"
@chooseavatar="onChooseAvatar"
>
<image class="w-8 h-8 rounded-full" :src="avatarUrl"></image>
<text class="ml-auto i-carbon-chevron-right"></text>
</button>
</view>
<view
class="flex items-center h-16 leading-16 border-b-gray-400 border-b-solid border-1 mt-4"
>
<text class="mr-4 flex-shrink-0">昵称</text>
<input type="nickname" placeholder="请输入昵称" @change="onChange" @blur="onChange" />
</view>
<button
size="default"
type="default"
style="color: #fff; background-color: #1aad19; border-color: #1aad19"
class="text-center leading-12 w-40 my-4"
@click="onSubmit"
>
确定
</button>
</view>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store'
import defaultAvatarUrl from './defaultAvatar.png'
const emit = defineEmits(['update:modelValue'])
defineProps<{ modelValue: boolean }>()
const userStore = useUserStore()
const avatarUrl = ref(defaultAvatarUrl)
const nickname = ref('')
const onClose = () => {
emit('update:modelValue', false)
}
const onChooseAvatar = (e) => {
const { avatarUrl: url } = e.detail
avatarUrl.value = url
// 这里就要上传,加快速度,提升体验(用户多次选择头像就多次上传吧,总有取舍)
console.log(url)
}
const onChange = (e) => {
const { value } = e.detail
nickname.value = value
console.log(value)
}
const onSubmit = () => {
// 1、上传刚刚的图片,并返回网络地址
// 2、把用户信息存起来
if (avatarUrl.value === defaultAvatarUrl) {
uni.showToast({
title: '请选择头像',
icon: 'none',
})
return
}
if (!nickname.value) {
uni.showToast({
title: '请填写昵称',
icon: 'none',
})
return
}
emit('update:modelValue', false)
console.log('保存用户信息')
userStore.setUserInfo({ nickname: nickname.value, avatar: avatarUrl.value })
}
</script>
<style lang="scss" scoped>
.fly-login {
position: fixed;
inset: 0;
.fly-login-mask {
position: fixed;
inset: 0;
background-color: rgb(0 0 0 / 30%);
}
.fly-login-content {
position: fixed;
right: 0;
bottom: var(--window-bottom);
left: 0;
background-color: #fff;
border-top-left-radius: 16px;
border-top-right-radius: 16px;
}
}
</style>
# fly-navbar
建议本导航栏组件在设置 `"navigationStyle": "custom"` 的页面使用,目前支持微信小程序的页面滚动动画。
<template>
<!-- 自定义导航栏: 默认透明不可见, scroll-view 滚动到 50 时展示 -->
<view class="fly-navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
<!-- 1/3,多于1个页面,用返回图标 -->
<navigator v-if="pages.length > 1" open-type="navigateBack" class="left-icon">
<view class="bg-gray-500/80 rounded-full w-8 h-8 flex items-center justify-center">
<button class="i-carbon-chevron-left text-white w-7 h-7"></button>
</view>
</navigator>
<!-- 2/3,只有1个页面,如果不是tabbar,需要首页图标 -->
<!-- 这种情况一般出现在用户直接打开分享出去的详情页面,或者使用redirectTo等API -->
<navigator
v-else-if="!isTabbar"
open-type="switchTab"
url="/pages/index/index"
class="left-icon"
>
<view class="bg-gray-500/80 rounded-full w-8 h-8 flex items-center justify-center">
<button class="i-carbon-home text-white w-6 h-6"></button>
</view>
</navigator>
<!-- 3/3,如果当前页就是tabbar页,不用去首页,也就是什么图标都不需要 -->
<view class="title">{{ title || '' }}</view>
</view>
</template>
<script lang="ts" setup>
import { getIsTabbar } from '@/utils/index'
defineProps<{ title?: string }>()
// 获取页面栈
const pages = getCurrentPages()
const isTabbar = getIsTabbar()
console.log({ isTabbar, pagesLen: pages.length })
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
</script>
<style lang="scss" scoped>
.fly-navbar {
position: fixed;
top: 0;
left: 0;
z-index: 9;
width: 750rpx;
color: #000;
background-color: transparent;
.left-icon {
position: absolute;
left: 0;
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
font-size: 44rpx;
color: #000;
}
.title {
display: flex;
align-items: center;
justify-content: center;
height: 44px;
font-size: 32rpx;
color: transparent;
}
}
</style>
/*
* uCharts®
* 高性能跨平台图表库,支持H5、APP、小程序(微信/支付宝/百度/头条/QQ/360)、Vue、Taro等支持canvas的框架平台
* Copyright (c) 2021 QIUN®秋云 https://www.ucharts.cn All rights reserved.
* Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
* 复制使用请保留本段注释,感谢支持开源!
*
* uCharts®官方网站
* https://www.uCharts.cn
*
* 开源地址:
* https://gitee.com/uCharts/uCharts
*
* uni-app插件市场地址:
* http://ext.dcloud.net.cn/plugin?id=271
*
*/
// 通用配置项
// 主题颜色配置:如每个图表类型需要不同主题,请在对应图表类型上更改color属性
const color = [
'#1890FF',
'#91CB74',
'#FAC858',
'#EE6666',
'#73C0DE',
'#3CA272',
'#FC8452',
'#9A60B4',
'#ea7ccc',
]
const cfe = {
// demotype为自定义图表类型
type: [
'pie',
'ring',
'rose',
'funnel',
'line',
'column',
'area',
'radar',
'gauge',
'candle',
'demotype',
],
// 增加自定义图表类型,如果需要categories,请在这里加入您的图表类型例如最后的"demotype"
categories: ['line', 'column', 'area', 'radar', 'gauge', 'candle', 'demotype'],
// instance为实例变量承载属性,option为eopts承载属性,不要删除
instance: {},
option: {},
// 下面是自定义format配置,因除H5端外的其他端无法通过props传递函数,只能通过此属性对应下标的方式来替换
formatter: {
tooltipDemo1(res) {
let result = ''
for (const i in res) {
if (i == 0) {
result += `${res[i].axisValueLabel}年销售额`
}
let value = '--'
if (res[i].data !== null) {
value = res[i].data
}
// #ifdef H5
result += `\n${res[i].seriesName}:${value} 万元`
// #endif
// #ifdef APP-PLUS
result += `<br/>${res[i].marker}${res[i].seriesName}:${value} 万元`
// #endif
}
return result
},
legendFormat(name) {
return `自定义图例+${name}`
},
yAxisFormatDemo(value, index) {
return `${value}元`
},
seriesFormatDemo(res) {
return `${res.name}年${res.value}元`
},
},
// 这里演示了自定义您的图表类型的option,可以随意命名,之后在组件上 type="demotype" 后,组件会调用这个花括号里的option,如果组件上还存在eopts参数,会将demotype与eopts中option合并后渲染图表。
demotype: {
color,
// 在这里填写echarts的option即可
},
// 下面是自定义配置,请添加项目所需的通用配置
column: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'axis',
},
grid: {
top: 30,
bottom: 50,
right: 15,
left: 40,
},
legend: {
bottom: 'left',
},
toolbox: {
show: false,
},
xAxis: {
type: 'category',
axisLabel: {
color: '#666666',
},
axisLine: {
lineStyle: {
color: '#CCCCCC',
},
},
boundaryGap: true,
data: [],
},
yAxis: {
type: 'value',
axisTick: {
show: false,
},
axisLabel: {
color: '#666666',
},
axisLine: {
lineStyle: {
color: '#CCCCCC',
},
},
},
seriesTemplate: {
name: '',
type: 'bar',
data: [],
barwidth: 20,
label: {
show: true,
color: '#666666',
position: 'top',
},
},
},
line: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'axis',
},
grid: {
top: 30,
bottom: 50,
right: 15,
left: 40,
},
legend: {
bottom: 'left',
},
toolbox: {
show: false,
},
xAxis: {
type: 'category',
axisLabel: {
color: '#666666',
},
axisLine: {
lineStyle: {
color: '#CCCCCC',
},
},
boundaryGap: true,
data: [],
},
yAxis: {
type: 'value',
axisTick: {
show: false,
},
axisLabel: {
color: '#666666',
},
axisLine: {
lineStyle: {
color: '#CCCCCC',
},
},
},
seriesTemplate: {
name: '',
type: 'line',
data: [],
barwidth: 20,
label: {
show: true,
color: '#666666',
position: 'top',
},
},
},
area: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'axis',
},
grid: {
top: 30,
bottom: 50,
right: 15,
left: 40,
},
legend: {
bottom: 'left',
},
toolbox: {
show: false,
},
xAxis: {
type: 'category',
axisLabel: {
color: '#666666',
},
axisLine: {
lineStyle: {
color: '#CCCCCC',
},
},
boundaryGap: true,
data: [],
},
yAxis: {
type: 'value',
axisTick: {
show: false,
},
axisLabel: {
color: '#666666',
},
axisLine: {
lineStyle: {
color: '#CCCCCC',
},
},
},
seriesTemplate: {
name: '',
type: 'line',
data: [],
areaStyle: {},
label: {
show: true,
color: '#666666',
position: 'top',
},
},
},
pie: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'item',
},
grid: {
top: 40,
bottom: 30,
right: 15,
left: 15,
},
legend: {
bottom: 'left',
},
seriesTemplate: {
name: '',
type: 'pie',
data: [],
radius: '50%',
label: {
show: true,
color: '#666666',
position: 'top',
},
},
},
ring: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'item',
},
grid: {
top: 40,
bottom: 30,
right: 15,
left: 15,
},
legend: {
bottom: 'left',
},
seriesTemplate: {
name: '',
type: 'pie',
data: [],
radius: ['40%', '70%'],
avoidLabelOverlap: false,
label: {
show: true,
color: '#666666',
position: 'top',
},
labelLine: {
show: true,
},
},
},
rose: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'item',
},
legend: {
top: 'bottom',
},
seriesTemplate: {
name: '',
type: 'pie',
data: [],
radius: '55%',
center: ['50%', '50%'],
roseType: 'area',
},
},
funnel: {
color,
title: {
text: '',
},
tooltip: {
trigger: 'item',
formatter: '{b} : {c}%',
},
legend: {
top: 'bottom',
},
seriesTemplate: {
name: '',
type: 'funnel',
left: '10%',
top: 60,
bottom: 60,
width: '80%',
min: 0,
max: 100,
minSize: '0%',
maxSize: '100%',
sort: 'descending',
gap: 2,
label: {
show: true,
position: 'inside',
},
labelLine: {
length: 10,
lineStyle: {
width: 1,
type: 'solid',
},
},
itemStyle: {
bordercolor: '#fff',
borderwidth: 1,
},
emphasis: {
label: {
fontSize: 20,
},
},
data: [],
},
},
gauge: {
color,
tooltip: {
formatter: '{a} <br/>{b} : {c}%',
},
seriesTemplate: {
name: '业务指标',
type: 'gauge',
detail: { formatter: '{value}%' },
data: [{ value: 50, name: '完成率' }],
},
},
candle: {
xAxis: {
data: [],
},
yAxis: {},
color,
title: {
text: '',
},
dataZoom: [
{
type: 'inside',
xAxisIndex: [0, 1],
start: 10,
end: 100,
},
{
show: true,
xAxisIndex: [0, 1],
type: 'slider',
bottom: 10,
start: 10,
end: 100,
},
],
seriesTemplate: {
name: '',
type: 'k',
data: [],
},
},
}
export default cfe
/*
* uCharts®
* 高性能跨平台图表库,支持H5、APP、小程序(微信/支付宝/百度/头条/QQ/360)、Vue、Taro等支持canvas的框架平台
* Copyright (c) 2021 QIUN®秋云 https://www.ucharts.cn All rights reserved.
* Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
* 复制使用请保留本段注释,感谢支持开源!
*
* uCharts®官方网站
* https://www.uCharts.cn
*
* 开源地址:
* https://gitee.com/uCharts/uCharts
*
* uni-app插件市场地址:
* http://ext.dcloud.net.cn/plugin?id=271
*
*/
// 主题颜色配置:如每个图表类型需要不同主题,请在对应图表类型上更改color属性
const color = [
'#1890FF',
'#91CB74',
'#FAC858',
'#EE6666',
'#73C0DE',
'#3CA272',
'#FC8452',
'#9A60B4',
'#ea7ccc',
]
// 事件转换函数,主要用作格式化x轴为时间轴,根据需求自行修改
const formatDateTime = (timeStamp, returnType) => {
const date = new Date()
date.setTime(timeStamp * 1000)
const y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? `0${m}` : m
let d = date.getDate()
d = d < 10 ? `0${d}` : d
let h = date.getHours()
h = h < 10 ? `0${h}` : h
let minute = date.getMinutes()
let second = date.getSeconds()
minute = minute < 10 ? `0${minute}` : minute
second = second < 10 ? `0${second}` : second
if (returnType == 'full') {
return `${y}-${m}-${d} ${h}:${minute}:${second}`
}
if (returnType == 'y-m-d') {
return `${y}-${m}-${d}`
}
if (returnType == 'h:m') {
return `${h}:${minute}`
}
if (returnType == 'h:m:s') {
return `${h}:${minute}:${second}`
}
return [y, m, d, h, minute, second]
}
const cfu = {
// demotype为自定义图表类型,一般不需要自定义图表类型,只需要改根节点上对应的类型即可
type: [
'pie',
'ring',
'rose',
'word',
'funnel',
'map',
'arcbar',
'line',
'column',
'mount',
'bar',
'area',
'radar',
'gauge',
'candle',
'mix',
'tline',
'tarea',
'scatter',
'bubble',
'demotype',
],
range: [
'饼状图',
'圆环图',
'玫瑰图',
'词云图',
'漏斗图',
'地图',
'圆弧进度条',
'折线图',
'柱状图',
'山峰图',
'条状图',
'区域图',
'雷达图',
'仪表盘',
'K线图',
'混合图',
'时间轴折线',
'时间轴区域',
'散点图',
'气泡图',
'自定义类型',
],
// 增加自定义图表类型,如果需要categories,请在这里加入您的图表类型,例如最后的"demotype"
// 自定义类型时需要注意"tline","tarea","scatter","bubble"等时间轴(矢量x轴)类图表,没有categories,不需要加入categories
categories: [
'line',
'column',
'mount',
'bar',
'area',
'radar',
'gauge',
'candle',
'mix',
'demotype',
],
// instance为实例变量承载属性,不要删除
instance: {},
// option为opts及eopts承载属性,不要删除
option: {},
// 下面是自定义format配置,因除H5端外的其他端无法通过props传递函数,只能通过此属性对应下标的方式来替换
formatter: {
yAxisDemo1(val, index, opts) {
return `${val}元`
},
yAxisDemo2(val, index, opts) {
return val.toFixed(2)
},
xAxisDemo1(val, index, opts) {
return `${val}年`
},
xAxisDemo2(val, index, opts) {
return formatDateTime(val, 'h:m')
},
seriesDemo1(val, index, series, opts) {
return `${val}元`
},
tooltipDemo1(item, category, index, opts) {
if (index == 0) {
return `随便用${item.data}年`
}
return `其他我没改${item.data}天`
},
pieDemo(val, index, series, opts) {
if (index !== undefined) {
return `${series[index].name}:${series[index].data}元`
}
},
},
// 这里演示了自定义您的图表类型的option,可以随意命名,之后在组件上 type="demotype" 后,组件会调用这个花括号里的option,如果组件上还存在opts参数,会将demotype与opts中option合并后渲染图表。
demotype: {
// 我这里把曲线图当做了自定义图表类型,您可以根据需要随意指定类型或配置
type: 'line',
color,
padding: [15, 10, 0, 15],
xAxis: {
disableGrid: true,
},
yAxis: {
gridType: 'dash',
dashLength: 2,
},
legend: {},
extra: {
line: {
type: 'curve',
width: 2,
},
},
},
// 下面是自定义配置,请添加项目所需的通用配置
pie: {
type: 'pie',
color,
padding: [5, 5, 5, 5],
extra: {
pie: {
activeOpacity: 0.5,
activeRadius: 10,
offsetAngle: 0,
labelWidth: 15,
border: true,
borderWidth: 3,
borderColor: '#FFFFFF',
},
},
},
ring: {
type: 'ring',
color,
padding: [5, 5, 5, 5],
rotate: false,
dataLabel: true,
legend: {
show: true,
position: 'right',
lineHeight: 25,
},
title: {
name: '收益率',
fontSize: 15,
color: '#666666',
},
subtitle: {
name: '70%',
fontSize: 25,
color: '#7cb5ec',
},
extra: {
ring: {
ringWidth: 30,
activeOpacity: 0.5,
activeRadius: 10,
offsetAngle: 0,
labelWidth: 15,
border: true,
borderWidth: 3,
borderColor: '#FFFFFF',
},
},
},
rose: {
type: 'rose',
color,
padding: [5, 5, 5, 5],
legend: {
show: true,
position: 'left',
lineHeight: 25,
},
extra: {
rose: {
type: 'area',
minRadius: 50,
activeOpacity: 0.5,
activeRadius: 10,
offsetAngle: 0,
labelWidth: 15,
border: false,
borderWidth: 2,
borderColor: '#FFFFFF',
},
},
},
word: {
type: 'word',
color,
extra: {
word: {
type: 'normal',
autoColors: false,
},
},
},
funnel: {
type: 'funnel',
color,
padding: [15, 15, 0, 15],
extra: {
funnel: {
activeOpacity: 0.3,
activeWidth: 10,
border: true,
borderWidth: 2,
borderColor: '#FFFFFF',
fillOpacity: 1,
labelAlign: 'right',
},
},
},
map: {
type: 'map',
color,
padding: [0, 0, 0, 0],
dataLabel: true,
extra: {
map: {
border: true,
borderWidth: 1,
borderColor: '#666666',
fillOpacity: 0.6,
activeBorderColor: '#F04864',
activeFillColor: '#FACC14',
activeFillOpacity: 1,
},
},
},
arcbar: {
type: 'arcbar',
color,
title: {
name: '百分比',
fontSize: 25,
color: '#00FF00',
},
subtitle: {
name: '默认标题',
fontSize: 15,
color: '#666666',
},
extra: {
arcbar: {
type: 'default',
width: 12,
backgroundColor: '#E9E9E9',
startAngle: 0.75,
endAngle: 0.25,
gap: 2,
},
},
},
line: {
type: 'line',
color,
padding: [15, 10, 0, 15],
xAxis: {
disableGrid: true,
},
yAxis: {
gridType: 'dash',
dashLength: 2,
},
legend: {},
extra: {
line: {
type: 'straight',
width: 2,
activeType: 'hollow',
},
},
},
tline: {
type: 'line',
color,
padding: [15, 10, 0, 15],
xAxis: {
disableGrid: false,
boundaryGap: 'justify',
},
yAxis: {
gridType: 'dash',
dashLength: 2,
data: [
{
min: 0,
max: 80,
},
],
},
legend: {},
extra: {
line: {
type: 'curve',
width: 2,
activeType: 'hollow',
},
},
},
tarea: {
type: 'area',
color,
padding: [15, 10, 0, 15],
xAxis: {
disableGrid: true,
boundaryGap: 'justify',
},
yAxis: {
gridType: 'dash',
dashLength: 2,
data: [
{
min: 0,
max: 80,
},
],
},
legend: {},
extra: {
area: {
type: 'curve',
opacity: 0.2,
addLine: true,
width: 2,
gradient: true,
activeType: 'hollow',
},
},
},
column: {
type: 'column',
color,
padding: [15, 15, 0, 5],
xAxis: {
disableGrid: true,
},
yAxis: {
data: [{ min: 0 }],
},
legend: {},
extra: {
column: {
type: 'group',
width: 30,
activeBgColor: '#000000',
activeBgOpacity: 0.08,
},
},
},
mount: {
type: 'mount',
color,
padding: [15, 15, 0, 5],
xAxis: {
disableGrid: true,
},
yAxis: {
data: [{ min: 0 }],
},
legend: {},
extra: {
mount: {
type: 'mount',
widthRatio: 1.5,
},
},
},
bar: {
type: 'bar',
color,
padding: [15, 30, 0, 5],
xAxis: {
boundaryGap: 'justify',
disableGrid: false,
min: 0,
axisLine: false,
},
yAxis: {},
legend: {},
extra: {
bar: {
type: 'group',
width: 30,
meterBorde: 1,
meterFillColor: '#FFFFFF',
activeBgColor: '#000000',
activeBgOpacity: 0.08,
},
},
},
area: {
type: 'area',
color,
padding: [15, 15, 0, 15],
xAxis: {
disableGrid: true,
},
yAxis: {
gridType: 'dash',
dashLength: 2,
},
legend: {},
extra: {
area: {
type: 'straight',
opacity: 0.2,
addLine: true,
width: 2,
gradient: false,
activeType: 'hollow',
},
},
},
radar: {
type: 'radar',
color,
padding: [5, 5, 5, 5],
dataLabel: false,
legend: {
show: true,
position: 'right',
lineHeight: 25,
},
extra: {
radar: {
gridType: 'radar',
gridColor: '#CCCCCC',
gridCount: 3,
opacity: 0.2,
max: 200,
labelShow: true,
},
},
},
gauge: {
type: 'gauge',
color,
title: {
name: '66Km/H',
fontSize: 25,
color: '#2fc25b',
offsetY: 50,
},
subtitle: {
name: '实时速度',
fontSize: 15,
color: '#1890ff',
offsetY: -50,
},
extra: {
gauge: {
type: 'default',
width: 30,
labelColor: '#666666',
startAngle: 0.75,
endAngle: 0.25,
startNumber: 0,
endNumber: 100,
labelFormat: '',
splitLine: {
fixRadius: 0,
splitNumber: 10,
width: 30,
color: '#FFFFFF',
childNumber: 5,
childWidth: 12,
},
pointer: {
width: 24,
color: 'auto',
},
},
},
},
candle: {
type: 'candle',
color,
padding: [15, 15, 0, 15],
enableScroll: true,
enableMarkLine: true,
dataLabel: false,
xAxis: {
labelCount: 4,
itemCount: 40,
disableGrid: true,
gridColor: '#CCCCCC',
gridType: 'solid',
dashLength: 4,
scrollShow: true,
scrollAlign: 'left',
scrollColor: '#A6A6A6',
scrollBackgroundColor: '#EFEBEF',
},
yAxis: {},
legend: {},
extra: {
candle: {
color: {
upLine: '#f04864',
upFill: '#f04864',
downLine: '#2fc25b',
downFill: '#2fc25b',
},
average: {
show: true,
name: ['MA5', 'MA10', 'MA30'],
day: [5, 10, 20],
color: ['#1890ff', '#2fc25b', '#facc14'],
},
},
markLine: {
type: 'dash',
dashLength: 5,
data: [
{
value: 2150,
lineColor: '#f04864',
showLabel: true,
},
{
value: 2350,
lineColor: '#f04864',
showLabel: true,
},
],
},
},
},
mix: {
type: 'mix',
color,
padding: [15, 15, 0, 15],
xAxis: {
disableGrid: true,
},
yAxis: {
disabled: false,
disableGrid: false,
splitNumber: 5,
gridType: 'dash',
dashLength: 4,
gridColor: '#CCCCCC',
padding: 10,
showTitle: true,
data: [],
},
legend: {},
extra: {
mix: {
column: {
width: 20,
},
},
},
},
scatter: {
type: 'scatter',
color,
padding: [15, 15, 0, 15],
dataLabel: false,
xAxis: {
disableGrid: false,
gridType: 'dash',
splitNumber: 5,
boundaryGap: 'justify',
min: 0,
},
yAxis: {
disableGrid: false,
gridType: 'dash',
},
legend: {},
extra: {
scatter: {},
},
},
bubble: {
type: 'bubble',
color,
padding: [15, 15, 0, 15],
xAxis: {
disableGrid: false,
gridType: 'dash',
splitNumber: 5,
boundaryGap: 'justify',
min: 0,
max: 250,
},
yAxis: {
disableGrid: false,
gridType: 'dash',
data: [
{
min: 0,
max: 150,
},
],
},
legend: {},
extra: {
bubble: {
border: 2,
opacity: 0.5,
},
},
},
}
export default cfu
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<!--
* qiun-data-charts 秋云高性能跨全端图表组件
* Copyright (c) 2021 QIUN® 秋云 https://www.ucharts.cn All rights reserved.
* Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
* 复制使用请保留本段注释,感谢支持开源!
* 为方便更多开发者使用,如有更好的建议请提交码云 Pull Requests !
*
* uCharts®官方网站
* https://www.uCharts.cn
*
* 开源地址:
* https://gitee.com/uCharts/uCharts
*
* uni-app插件市场地址:
* http://ext.dcloud.net.cn/plugin?id=271
*
-->
<template>
<view class="chartsview" :id="'ChartBoxId' + cid">
<view v-if="mixinDatacomLoading">
<!-- 自定义加载状态,请改这里 -->
<qiun-loading :loadingType="loadingType" />
</view>
<view v-if="mixinDatacomErrorMessage && errorShow" @tap="reloading">
<!-- 自定义错误提示,请改这里 -->
<qiun-error :errorMessage="errorMessage" />
</view>
<!-- APP和H5采用renderjs渲染图表 -->
<!-- #ifdef APP-VUE || H5 -->
<block v-if="echarts">
<view
:style="{ background: background }"
style="width: 100%; height: 100%"
:data-directory="directory"
:id="'EC' + cid"
:prop="echartsOpts"
:change:prop="rdcharts.ecinit"
:resize="echartsResize"
:change:resize="rdcharts.ecresize"
v-show="showchart"
/>
</block>
<block v-else>
<view
v-on:tap="rdcharts.tap"
v-on:mousemove="rdcharts.mouseMove"
v-on:mousedown="rdcharts.mouseDown"
v-on:mouseup="rdcharts.mouseUp"
v-on:touchstart="rdcharts.touchStart"
v-on:touchmove="rdcharts.touchMove"
v-on:touchend="rdcharts.touchEnd"
:id="'UC' + cid"
:prop="uchartsOpts"
:change:prop="rdcharts.ucinit"
>
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disableScroll"
@error="_error"
v-show="showchart"
/>
</view>
</block>
<!-- #endif -->
<!-- 支付宝小程序 -->
<!-- #ifdef MP-ALIPAY -->
<block v-if="ontouch">
<canvas
:id="cid"
:canvasId="cid"
:width="cWidth * pixel"
:height="cHeight * pixel"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disScroll"
@tap="_tap"
@touchstart="_touchStart"
@touchmove="_touchMove"
@touchend="_touchEnd"
@error="_error"
v-show="showchart"
/>
</block>
<block v-if="!ontouch">
<canvas
:id="cid"
:canvasId="cid"
:width="cWidth * pixel"
:height="cHeight * pixel"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disScroll"
@tap="_tap"
@error="_error"
v-show="showchart"
/>
</block>
<!-- #endif -->
<!-- 其他小程序通过vue渲染图表 -->
<!-- #ifdef MP-WEIXIN || MP-BAIDU || MP-QQ || MP-TOUTIAO || MP-KUAISHOU || MP-LARK || MP-JD || MP-360 -->
<block v-if="type2d">
<view v-if="ontouch" @tap="_tap">
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
type="2d"
:disable-scroll="disScroll"
@touchstart="_touchStart"
@touchmove="_touchMove"
@touchend="_touchEnd"
@error="_error"
v-show="showchart"
/>
</view>
<view v-if="!ontouch" @tap="_tap">
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
type="2d"
:disable-scroll="disScroll"
@error="_error"
v-show="showchart"
/>
</view>
</block>
<block v-if="!type2d">
<view v-if="ontouch" @tap="_tap">
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
@touchstart="_touchStart"
@touchmove="_touchMove"
@touchend="_touchEnd"
:disable-scroll="disScroll"
@error="_error"
v-if="showchart"
/>
</view>
<view v-if="!ontouch">
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disScroll"
@tap="_tap"
@error="_error"
v-if="showchart"
/>
</view>
</block>
<!-- #endif -->
</view>
</template>
<script>
import uChartsMp from './u-charts.js'
import cfu from './config-ucharts.js'
// #ifdef APP-VUE || H5
import cfe from './config-echarts.js'
// #endif
function deepCloneAssign(origin = {}, ...args) {
for (const i in args) {
for (const key in args[i]) {
if (args[i].hasOwnProperty(key)) {
origin[key] =
args[i][key] && typeof args[i][key] === 'object'
? deepCloneAssign(Array.isArray(args[i][key]) ? [] : {}, origin[key], args[i][key])
: args[i][key]
}
}
}
return origin
}
function formatterAssign(args, formatter) {
for (const key in args) {
if (args.hasOwnProperty(key) && args[key] !== null && typeof args[key] === 'object') {
formatterAssign(args[key], formatter)
} else if (key === 'format' && typeof args[key] === 'string') {
args.formatter = formatter[args[key]] ? formatter[args[key]] : undefined
}
}
return args
}
// 时间转换函数,为了匹配uniClinetDB读取出的时间与categories不同
function getFormatDate(date) {
const seperator = '-'
const year = date.getFullYear()
let month = date.getMonth() + 1
let strDate = date.getDate()
if (month >= 1 && month <= 9) {
month = `0${month}`
}
if (strDate >= 0 && strDate <= 9) {
strDate = `0${strDate}`
}
const currentdate = year + seperator + month + seperator + strDate
return currentdate
}
let lastMoveTime = null
/**
* 防抖
*
* @param { Function } fn 要执行的方法
* @param { Number } wait 防抖多少毫秒
*
* 在 vue 中使用(注意:不能使用箭头函数,否则this指向不对,并且不能再次封装如:
* move(){ // 错误调用方式
* debounce(function () {
* console.log(this.title);
* }, 1000)});
* 应该直接使用:// 正确调用方式
* move: debounce(function () {
* console.log(this.title);
* }, 1000)
*/
function debounce(fn, wait) {
let timer = false
return function () {
clearTimeout(timer)
timer && clearTimeout(timer)
timer = setTimeout(() => {
timer = false
fn.apply(this, arguments) // 把参数传进去
}, wait)
}
}
export default {
name: 'qiun-data-charts',
mixins: [uniCloud.mixinDatacom],
props: {
type: {
type: String,
default: null,
},
canvasId: {
type: String,
default: 'uchartsid',
},
canvas2d: {
type: Boolean,
default: false,
},
background: {
type: String,
default: 'none',
},
animation: {
type: Boolean,
default: true,
},
chartData: {
type: Object,
default() {
return {
categories: [],
series: [],
}
},
},
opts: {
type: Object,
default() {
return {}
},
},
eopts: {
type: Object,
default() {
return {}
},
},
loadingType: {
type: Number,
default: 2,
},
errorShow: {
type: Boolean,
default: true,
},
errorReload: {
type: Boolean,
default: true,
},
errorMessage: {
type: String,
default: null,
},
inScrollView: {
type: Boolean,
default: false,
},
reshow: {
type: Boolean,
default: false,
},
reload: {
type: Boolean,
default: false,
},
disableScroll: {
type: Boolean,
default: false,
},
optsWatch: {
type: Boolean,
default: true,
},
onzoom: {
type: Boolean,
default: false,
},
ontap: {
type: Boolean,
default: true,
},
ontouch: {
type: Boolean,
default: false,
},
onmouse: {
type: Boolean,
default: true,
},
onmovetip: {
type: Boolean,
default: false,
},
echartsH5: {
type: Boolean,
default: false,
},
echartsApp: {
type: Boolean,
default: false,
},
tooltipShow: {
type: Boolean,
default: true,
},
tooltipFormat: {
type: String,
default: undefined,
},
tooltipCustom: {
type: Object,
default: undefined,
},
startDate: {
type: String,
default: undefined,
},
endDate: {
type: String,
default: undefined,
},
textEnum: {
type: Array,
default() {
return []
},
},
groupEnum: {
type: Array,
default() {
return []
},
},
pageScrollTop: {
type: Number,
default: 0,
},
directory: {
type: String,
default: '/',
},
tapLegend: {
type: Boolean,
default: true,
},
},
data() {
return {
cid: 'uchartsid',
inWx: false,
inAli: false,
inTt: false,
inBd: false,
inH5: false,
inApp: false,
inWin: false,
type2d: true,
disScroll: false,
openmouse: false,
pixel: 1,
cWidth: 375,
cHeight: 250,
showchart: false,
echarts: false,
echartsResize: {
state: false,
},
uchartsOpts: {},
echartsOpts: {},
drawData: {},
lastDrawTime: null,
}
},
created() {
this.cid = this.canvasId
if (this.canvasId == 'uchartsid' || this.canvasId == '') {
const t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
const len = t.length
let id = ''
for (let i = 0; i < 32; i++) {
id += t.charAt(Math.floor(Math.random() * len))
}
this.cid = id
}
const systemInfo = uni.getSystemInfoSync()
if (systemInfo.platform === 'windows' || systemInfo.platform === 'macos') {
this.inWin = true
}
// #ifdef MP-WEIXIN
this.inWx = true
if (
this.canvas2d === false ||
systemInfo.platform === 'windows' ||
systemInfo.platform === 'macos'
) {
this.type2d = false
} else {
this.type2d = true
this.pixel = systemInfo.pixelRatio
}
// #endif
// 非微信小程序端强制关闭canvas2d模式
// #ifndef MP-WEIXIN
this.type2d = false
// #endif
// #ifdef MP-KUAISHOU
this.type2d = true
// #endif
// #ifdef MP-TOUTIAO || MP-LARK || MP-ALIPAY
this.type2d = this.canvas2d
if (this.canvas2d === true) {
this.pixel = systemInfo.pixelRatio
}
// #endif
// #ifdef MP-ALIPAY
this.inAli = true
this.pixel = systemInfo.pixelRatio
// #endif
// #ifdef MP-BAIDU
this.inBd = true
// #endif
// #ifdef MP-TOUTIAO
this.inTt = true
// #endif
this.disScroll = this.disableScroll
},
mounted() {
// #ifdef APP-VUE
this.inApp = true
if (this.echartsApp === true) {
this.echarts = true
this.openmouse = false
}
// #endif
// #ifdef APP-NVUE
this.inApp = true
this.mixinDatacomLoading = false
this.mixinDatacomErrorMessage = '暂不支持NVUE'
// #endif
// #ifdef H5
this.inH5 = true
if (this.inWin === true) {
this.openmouse = this.onmouse
}
if (this.echartsH5 === true) {
this.echarts = true
}
// #endif
this.$nextTick(() => {
this.beforeInit()
})
// #ifdef MP-WEIXIN || H5
const time = this.inH5 ? 500 : 200
const _this = this
uni.onWindowResize(
debounce(function (res) {
if (_this.mixinDatacomLoading == true) {
return
}
const errmsg = _this.mixinDatacomErrorMessage
if (errmsg !== null && errmsg !== 'null' && errmsg !== '') {
return
}
if (_this.echarts) {
_this.echartsResize.state = !_this.echartsResize.state
} else {
_this.resizeHandler()
}
}, time),
)
// #endif
},
unmounted() {
if (this.echarts === true) {
delete cfe.option[this.cid]
delete cfe.instance[this.cid]
} else {
delete cfu.option[this.cid]
delete cfu.instance[this.cid]
}
// #ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
uni.offWindowResize(() => {})
// #endif
},
watch: {
chartDataProps: {
handler(val, oldval) {
if (typeof val === 'object') {
if (JSON.stringify(val) !== JSON.stringify(oldval)) {
this._clearChart()
if (val.series && val.series.length > 0) {
this.beforeInit()
} else {
this.mixinDatacomLoading = true
this.showchart = false
this.mixinDatacomErrorMessage = null
}
}
} else {
this.mixinDatacomLoading = false
this._clearChart()
this.showchart = false
this.mixinDatacomErrorMessage = '参数错误:chartData数据类型错误'
}
},
immediate: false,
deep: true,
},
localdata: {
handler(val, oldval) {
if (JSON.stringify(val) !== JSON.stringify(oldval)) {
if (val.length > 0) {
this.beforeInit()
} else {
this.mixinDatacomLoading = true
this._clearChart()
this.showchart = false
this.mixinDatacomErrorMessage = null
}
}
},
immediate: false,
deep: true,
},
optsProps: {
handler(val, oldval) {
if (typeof val === 'object') {
if (
JSON.stringify(val) !== JSON.stringify(oldval) &&
this.echarts === false &&
this.optsWatch == true
) {
this.checkData(this.drawData)
}
} else {
this.mixinDatacomLoading = false
this._clearChart()
this.showchart = false
this.mixinDatacomErrorMessage = '参数错误:opts数据类型错误'
}
},
immediate: false,
deep: true,
},
eoptsProps: {
handler(val, oldval) {
if (typeof val === 'object') {
if (JSON.stringify(val) !== JSON.stringify(oldval) && this.echarts === true) {
this.checkData(this.drawData)
}
} else {
this.mixinDatacomLoading = false
this.showchart = false
this.mixinDatacomErrorMessage = '参数错误:eopts数据类型错误'
}
},
immediate: false,
deep: true,
},
reshow(val, oldval) {
if (val === true && this.mixinDatacomLoading === false) {
setTimeout(() => {
this.mixinDatacomErrorMessage = null
this.echartsResize.state = !this.echartsResize.state
this.checkData(this.drawData)
}, 200)
}
},
reload(val, oldval) {
if (val === true) {
this.showchart = false
this.mixinDatacomErrorMessage = null
this.reloading()
}
},
mixinDatacomErrorMessage(val, oldval) {
if (val) {
this.emitMsg({
name: 'error',
params: { type: 'error', errorShow: this.errorShow, msg: val, id: this.cid },
})
if (this.errorShow) {
console.log(`[秋云图表组件]${val}`)
}
}
},
errorMessage(val, oldval) {
if (val && this.errorShow && val !== null && val !== 'null' && val !== '') {
this.showchart = false
this.mixinDatacomLoading = false
this.mixinDatacomErrorMessage = val
} else {
this.showchart = false
this.mixinDatacomErrorMessage = null
this.reloading()
}
},
},
computed: {
optsProps() {
return JSON.parse(JSON.stringify(this.opts))
},
eoptsProps() {
return JSON.parse(JSON.stringify(this.eopts))
},
chartDataProps() {
return JSON.parse(JSON.stringify(this.chartData))
},
},
methods: {
beforeInit() {
this.mixinDatacomErrorMessage = null
if (
typeof this.chartData === 'object' &&
this.chartData != null &&
this.chartData.series !== undefined &&
this.chartData.series.length > 0
) {
// 拷贝一下chartData,为了opts变更后统一数据来源
this.drawData = deepCloneAssign({}, this.chartData)
this.mixinDatacomLoading = false
this.showchart = true
this.checkData(this.chartData)
} else if (this.localdata.length > 0) {
this.mixinDatacomLoading = false
this.showchart = true
this.localdataInit(this.localdata)
} else if (this.collection !== '') {
this.mixinDatacomLoading = false
this.getCloudData()
} else {
this.mixinDatacomLoading = true
}
},
localdataInit(resdata) {
// 替换enum类型为正确的描述
if (this.groupEnum.length > 0) {
for (let i = 0; i < resdata.length; i++) {
for (let j = 0; j < this.groupEnum.length; j++) {
if (resdata[i].group === this.groupEnum[j].value) {
resdata[i].group = this.groupEnum[j].text
}
}
}
}
if (this.textEnum.length > 0) {
for (let i = 0; i < resdata.length; i++) {
for (let j = 0; j < this.textEnum.length; j++) {
if (resdata[i].text === this.textEnum[j].value) {
resdata[i].text = this.textEnum[j].text
}
}
}
}
let needCategories = false
const tmpData = { categories: [], series: [] }
let tmpcategories = []
let tmpseries = []
// 拼接categories
if (this.echarts === true) {
needCategories = cfe.categories.includes(this.type)
} else {
needCategories = cfu.categories.includes(this.type)
}
if (needCategories === true) {
// 如果props中的chartData带有categories,则优先使用chartData的categories
if (this.chartData && this.chartData.categories && this.chartData.categories.length > 0) {
tmpcategories = this.chartData.categories
} else {
// 如果是日期类型的数据,不管是本地数据还是云数据,都按起止日期自动拼接categories
if (this.startDate && this.endDate) {
let idate = new Date(this.startDate)
const edate = new Date(this.endDate)
while (idate <= edate) {
tmpcategories.push(getFormatDate(idate))
idate = idate.setDate(idate.getDate() + 1)
idate = new Date(idate)
}
// 否则从结果中去重并拼接categories
} else {
const tempckey = {}
resdata.map(function (item, index) {
if (item.text != undefined && !tempckey[item.text]) {
tmpcategories.push(item.text)
tempckey[item.text] = true
}
})
}
}
tmpData.categories = tmpcategories
}
// 拼接series
const tempskey = {}
resdata.map(function (item, index) {
if (item.group != undefined && !tempskey[item.group]) {
tmpseries.push({ name: item.group, data: [] })
tempskey[item.group] = true
}
})
// 如果没有获取到分组名称(可能是带categories的数据,也可能是不带的饼图类)
if (tmpseries.length == 0) {
tmpseries = [{ name: '默认分组', data: [] }]
// 如果是需要categories的图表类型
if (needCategories === true) {
for (let j = 0; j < tmpcategories.length; j++) {
let seriesdata = 0
for (let i = 0; i < resdata.length; i++) {
if (resdata[i].text == tmpcategories[j]) {
seriesdata = resdata[i].value
}
}
tmpseries[0].data.push(seriesdata)
}
// 如果是饼图类的图表类型
} else {
for (let i = 0; i < resdata.length; i++) {
tmpseries[0].data.push({ name: resdata[i].text, value: resdata[i].value })
}
}
// 如果有分组名
} else {
for (let k = 0; k < tmpseries.length; k++) {
// 如果有categories
if (tmpcategories.length > 0) {
for (let j = 0; j < tmpcategories.length; j++) {
let seriesdata = 0
for (let i = 0; i < resdata.length; i++) {
if (tmpseries[k].name == resdata[i].group && resdata[i].text == tmpcategories[j]) {
seriesdata = resdata[i].value
}
}
tmpseries[k].data.push(seriesdata)
}
// 如果传了group而没有传text,即没有categories(正常情况下这种数据是不符合数据要求规范的)
} else {
for (let i = 0; i < resdata.length; i++) {
if (tmpseries[k].name == resdata[i].group) {
tmpseries[k].data.push(resdata[i].value)
}
}
}
}
}
tmpData.series = tmpseries
// 拷贝一下chartData,为了opts变更后统一数据来源
this.drawData = deepCloneAssign({}, tmpData)
this.checkData(tmpData)
},
reloading() {
if (this.errorReload === false) {
return
}
this.showchart = false
this.mixinDatacomErrorMessage = null
if (this.collection !== '') {
this.mixinDatacomLoading = false
this.onMixinDatacomPropsChange(true)
} else {
this.beforeInit()
}
},
checkData(anyData) {
const { cid } = this
// 复位opts或eopts
if (this.echarts === true) {
cfe.option[cid] = deepCloneAssign({}, this.eopts)
cfe.option[cid].id = cid
cfe.option[cid].type = this.type
} else if (this.type && cfu.type.includes(this.type)) {
cfu.option[cid] = deepCloneAssign({}, cfu[this.type], this.opts)
cfu.option[cid].canvasId = cid
} else {
this.mixinDatacomLoading = false
this.showchart = false
this.mixinDatacomErrorMessage = '参数错误:props参数中type类型不正确'
}
// 挂载categories和series
const newData = deepCloneAssign({}, anyData)
if (newData.series !== undefined && newData.series.length > 0) {
this.mixinDatacomErrorMessage = null
if (this.echarts === true) {
cfe.option[cid].chartData = newData
this.$nextTick(() => {
this.init()
})
} else {
cfu.option[cid].categories = newData.categories
cfu.option[cid].series = newData.series
this.$nextTick(() => {
this.init()
})
}
}
},
resizeHandler() {
// 渲染防抖
const currTime = Date.now()
const lastDrawTime = this.lastDrawTime ? this.lastDrawTime : currTime - 3000
const duration = currTime - lastDrawTime
if (duration < 1000) return
const chartdom = uni
.createSelectorQuery()
// #ifndef MP-ALIPAY
.in(this)
// #endif
.select(`#ChartBoxId${this.cid}`)
.boundingClientRect((data) => {
this.showchart = true
if (data.width > 0 && data.height > 0) {
if (data.width !== this.cWidth || data.height !== this.cHeight) {
this.checkData(this.drawData)
}
}
})
.exec()
},
getCloudData() {
if (this.mixinDatacomLoading == true) {
return
}
this.mixinDatacomLoading = true
this.mixinDatacomGet()
.then((res) => {
this.mixinDatacomResData = res.result.data
this.localdataInit(this.mixinDatacomResData)
})
.catch((err) => {
this.mixinDatacomLoading = false
this.showchart = false
this.mixinDatacomErrorMessage = `请求错误:${err}`
})
},
onMixinDatacomPropsChange(needReset, changed) {
if (needReset == true && this.collection !== '') {
this.showchart = false
this.mixinDatacomErrorMessage = null
this._clearChart()
this.getCloudData()
}
},
_clearChart() {
const { cid } = this
if (this.echarts !== true && cfu.option[cid] && cfu.option[cid].context) {
const ctx = cfu.option[cid].context
if (typeof ctx === 'object' && !cfu.option[cid].update) {
ctx.clearRect(0, 0, this.cWidth * this.pixel, this.cHeight * this.pixel)
ctx.draw()
}
}
},
init() {
const { cid } = this
const chartdom = uni
.createSelectorQuery()
// #ifndef MP-ALIPAY
.in(this)
// #endif
.select(`#ChartBoxId${cid}`)
.boundingClientRect((data) => {
if (data.width > 0 && data.height > 0) {
this.mixinDatacomLoading = false
this.showchart = true
this.lastDrawTime = Date.now()
this.cWidth = data.width
this.cHeight = data.height
if (this.echarts !== true) {
cfu.option[cid].background = this.background == 'none' ? '#FFFFFF' : this.background
cfu.option[cid].canvas2d = this.type2d
cfu.option[cid].pixelRatio = this.pixel
cfu.option[cid].animation = this.animation
cfu.option[cid].width = data.width * this.pixel
cfu.option[cid].height = data.height * this.pixel
cfu.option[cid].onzoom = this.onzoom
cfu.option[cid].ontap = this.ontap
cfu.option[cid].ontouch = this.ontouch
cfu.option[cid].onmouse = this.openmouse
cfu.option[cid].onmovetip = this.onmovetip
cfu.option[cid].tooltipShow = this.tooltipShow
cfu.option[cid].tooltipFormat = this.tooltipFormat
cfu.option[cid].tooltipCustom = this.tooltipCustom
cfu.option[cid].inScrollView = this.inScrollView
cfu.option[cid].lastDrawTime = this.lastDrawTime
cfu.option[cid].tapLegend = this.tapLegend
}
// 如果是H5或者App端,采用renderjs渲染图表
if (this.inH5 || this.inApp) {
if (this.echarts == true) {
cfe.option[cid].ontap = this.ontap
cfe.option[cid].onmouse = this.openmouse
cfe.option[cid].tooltipShow = this.tooltipShow
cfe.option[cid].tooltipFormat = this.tooltipFormat
cfe.option[cid].tooltipCustom = this.tooltipCustom
cfe.option[cid].lastDrawTime = this.lastDrawTime
this.echartsOpts = deepCloneAssign({}, cfe.option[cid])
} else {
cfu.option[cid].rotateLock = cfu.option[cid].rotate
this.uchartsOpts = deepCloneAssign({}, cfu.option[cid])
}
// 如果是小程序端,采用uCharts渲染
} else {
cfu.option[cid] = formatterAssign(cfu.option[cid], cfu.formatter)
this.mixinDatacomErrorMessage = null
this.mixinDatacomLoading = false
this.showchart = true
this.$nextTick(() => {
if (this.type2d === true) {
const query = uni.createSelectorQuery().in(this)
query
.select(`#${cid}`)
.fields({ node: true, size: true })
.exec((res) => {
if (res[0]) {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
cfu.option[cid].context = ctx
cfu.option[cid].rotateLock = cfu.option[cid].rotate
if (
cfu.instance[cid] &&
cfu.option[cid] &&
cfu.option[cid].update === true
) {
this._updataUChart(cid)
} else {
canvas.width = data.width * this.pixel
canvas.height = data.height * this.pixel
canvas._width = data.width * this.pixel
canvas._height = data.height * this.pixel
setTimeout(() => {
cfu.option[cid].context.restore()
cfu.option[cid].context.save()
this._newChart(cid)
}, 100)
}
} else {
this.showchart = false
this.mixinDatacomErrorMessage = `参数错误:开启2d模式后,未获取到dom节点,canvas-id:${cid}`
}
})
} else {
if (this.inAli) {
cfu.option[cid].rotateLock = cfu.option[cid].rotate
}
cfu.option[cid].context = uni.createCanvasContext(cid, this)
if (cfu.instance[cid] && cfu.option[cid] && cfu.option[cid].update === true) {
this._updataUChart(cid)
} else {
setTimeout(() => {
cfu.option[cid].context.restore()
cfu.option[cid].context.save()
this._newChart(cid)
}, 100)
}
}
})
}
} else {
this.mixinDatacomLoading = false
this.showchart = false
if (this.reshow == true) {
this.mixinDatacomErrorMessage = `布局错误:未获取到父元素宽高尺寸!canvas-id:${cid}`
}
}
})
.exec()
},
saveImage() {
uni.canvasToTempFilePath(
{
canvasId: this.cid,
success: (res) => {
// #ifdef H5
const a = document.createElement('a')
a.href = res.tempFilePath
a.download = this.cid
a.target = '_blank'
a.click()
// #endif
// #ifndef H5
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success() {
uni.showToast({
title: '保存成功',
duration: 2000,
})
},
})
// #endif
},
},
this,
)
},
getImage() {
if (this.type2d == false) {
uni.canvasToTempFilePath(
{
canvasId: this.cid,
success: (res) => {
this.emitMsg({
name: 'getImage',
params: { type: 'getImage', base64: res.tempFilePath },
})
},
},
this,
)
} else {
const query = uni.createSelectorQuery().in(this)
query
.select(`#${this.cid}`)
.fields({ node: true, size: true })
.exec((res) => {
if (res[0]) {
const canvas = res[0].node
this.emitMsg({
name: 'getImage',
params: { type: 'getImage', base64: canvas.toDataURL('image/png') },
})
}
})
}
},
// #ifndef APP-VUE || H5
_newChart(cid) {
if (this.mixinDatacomLoading == true) {
return
}
this.showchart = true
cfu.instance[cid] = new uChartsMp(cfu.option[cid])
cfu.instance[cid].addEventListener('renderComplete', () => {
this.emitMsg({
name: 'complete',
params: { type: 'complete', complete: true, id: cid, opts: cfu.instance[cid].opts },
})
cfu.instance[cid].delEventListener('renderComplete')
})
cfu.instance[cid].addEventListener('scrollLeft', () => {
this.emitMsg({
name: 'scrollLeft',
params: { type: 'scrollLeft', scrollLeft: true, id: cid, opts: cfu.instance[cid].opts },
})
})
cfu.instance[cid].addEventListener('scrollRight', () => {
this.emitMsg({
name: 'scrollRight',
params: { type: 'scrollRight', scrollRight: true, id: cid, opts: cfu.instance[cid].opts },
})
})
},
_updataUChart(cid) {
cfu.instance[cid].updateData(cfu.option[cid])
},
_tooltipDefault(item, category, index, opts) {
if (category) {
let { data } = item
if (typeof item.data === 'object') {
data = item.data.value
}
return `${category} ${item.name}:${data}`
}
if (item.properties && item.properties.name) {
return item.properties.name
}
return `${item.name}:${item.data}`
},
_showTooltip(e) {
const { cid } = this
const tc = cfu.option[cid].tooltipCustom
if (tc && tc !== undefined && tc !== null) {
let offset
if (tc.x >= 0 && tc.y >= 0) {
offset = { x: tc.x, y: tc.y + 10 }
}
cfu.instance[cid].showToolTip(e, {
index: tc.index,
offset,
textList: tc.textList,
formatter: (item, category, index, opts) => {
if (
typeof cfu.option[cid].tooltipFormat === 'string' &&
cfu.formatter[cfu.option[cid].tooltipFormat]
) {
return cfu.formatter[cfu.option[cid].tooltipFormat](item, category, index, opts)
}
return this._tooltipDefault(item, category, index, opts)
},
})
} else {
cfu.instance[cid].showToolTip(e, {
formatter: (item, category, index, opts) => {
if (
typeof cfu.option[cid].tooltipFormat === 'string' &&
cfu.formatter[cfu.option[cid].tooltipFormat]
) {
return cfu.formatter[cfu.option[cid].tooltipFormat](item, category, index, opts)
}
return this._tooltipDefault(item, category, index, opts)
},
})
}
},
_tap(e, move) {
const { cid } = this
let currentIndex = null
let legendIndex = null
if (this.inScrollView === true || this.inAli) {
const chartdom = uni
.createSelectorQuery()
// #ifndef MP-ALIPAY
.in(this)
.select(`#ChartBoxId${cid}`)
// #endif
// #ifdef MP-ALIPAY
.select(`#${this.cid}`)
// #endif
.boundingClientRect((data) => {
e.changedTouches = []
if (this.inAli) {
e.changedTouches.unshift({
x: e.detail.clientX - data.left,
y: e.detail.clientY - data.top,
})
} else {
e.changedTouches.unshift({
x: e.detail.x - data.left,
y: e.detail.y - data.top - this.pageScrollTop,
})
}
if (move) {
if (this.tooltipShow === true) {
this._showTooltip(e)
}
} else {
currentIndex = cfu.instance[cid].getCurrentDataIndex(e)
legendIndex = cfu.instance[cid].getLegendDataIndex(e)
if (this.tapLegend === true) {
cfu.instance[cid].touchLegend(e)
}
if (this.tooltipShow === true) {
this._showTooltip(e)
}
this.emitMsg({
name: 'getIndex',
params: {
type: 'getIndex',
event: { x: e.detail.x - data.left, y: e.detail.y - data.top },
currentIndex,
legendIndex,
id: cid,
opts: cfu.instance[cid].opts,
},
})
}
})
.exec()
} else if (move) {
if (this.tooltipShow === true) {
this._showTooltip(e)
}
} else {
e.changedTouches = []
e.changedTouches.unshift({
x: e.detail.x - e.currentTarget.offsetLeft,
y: e.detail.y - e.currentTarget.offsetTop,
})
currentIndex = cfu.instance[cid].getCurrentDataIndex(e)
legendIndex = cfu.instance[cid].getLegendDataIndex(e)
if (this.tapLegend === true) {
cfu.instance[cid].touchLegend(e)
}
if (this.tooltipShow === true) {
this._showTooltip(e)
}
this.emitMsg({
name: 'getIndex',
params: {
type: 'getIndex',
event: { x: e.detail.x, y: e.detail.y - e.currentTarget.offsetTop },
currentIndex,
legendIndex,
id: cid,
opts: cfu.instance[cid].opts,
},
})
}
},
_touchStart(e) {
const { cid } = this
lastMoveTime = Date.now()
if (cfu.option[cid].enableScroll === true && e.touches.length == 1) {
cfu.instance[cid].scrollStart(e)
}
this.emitMsg({
name: 'getTouchStart',
params: {
type: 'touchStart',
event: e.changedTouches[0],
id: cid,
opts: cfu.instance[cid].opts,
},
})
},
_touchMove(e) {
const { cid } = this
const currMoveTime = Date.now()
const duration = currMoveTime - lastMoveTime
const touchMoveLimit = cfu.option[cid].touchMoveLimit || 24
if (duration < Math.floor(1000 / touchMoveLimit)) return // 每秒60帧
lastMoveTime = currMoveTime
if (cfu.option[cid].enableScroll === true && e.changedTouches.length == 1) {
cfu.instance[cid].scroll(e)
}
if (
this.ontap === true &&
cfu.option[cid].enableScroll === false &&
this.onmovetip === true
) {
this._tap(e, true)
}
if (
this.ontouch === true &&
cfu.option[cid].enableScroll === true &&
this.onzoom === true &&
e.changedTouches.length == 2
) {
cfu.instance[cid].dobuleZoom(e)
}
this.emitMsg({
name: 'getTouchMove',
params: {
type: 'touchMove',
event: e.changedTouches[0],
id: cid,
opts: cfu.instance[cid].opts,
},
})
},
_touchEnd(e) {
const { cid } = this
if (cfu.option[cid].enableScroll === true && e.touches.length == 0) {
cfu.instance[cid].scrollEnd(e)
}
this.emitMsg({
name: 'getTouchEnd',
params: {
type: 'touchEnd',
event: e.changedTouches[0],
id: cid,
opts: cfu.instance[cid].opts,
},
})
if (
this.ontap === true &&
cfu.option[cid].enableScroll === false &&
this.onmovetip === true
) {
this._tap(e, true)
}
},
// #endif
_error(e) {
this.mixinDatacomErrorMessage = e.detail.errMsg
},
emitMsg(msg) {
this.$emit(msg.name, msg.params)
},
getRenderType() {
// 防止如果开启echarts且父元素为v-if的情况renderjs监听不到prop变化的问题
if (this.echarts === true && this.mixinDatacomLoading === false) {
this.beforeInit()
}
},
toJSON() {
return this
},
},
}
</script>
<!-- #ifdef APP-VUE || H5 -->
<script module="rdcharts" lang="renderjs">
import uChartsRD from './u-charts.js';
import cfu from './config-ucharts.js';
import cfe from './config-echarts.js';
var that = {};
var rootdom = null;
function rddeepCloneAssign(origin = {}, ...args) {
for (let i in args) {
for (let key in args[i]) {
if (args[i].hasOwnProperty(key)) {
origin[key] = args[i][key] && typeof args[i][key] === 'object' ? rddeepCloneAssign(Array.isArray(args[i][key]) ? [] : {}, origin[key], args[i][key]) : args[i][key];
}
}
}
return origin;
}
function rdformatterAssign(args,formatter) {
for (let key in args) {
if(args.hasOwnProperty(key) && args[key] !== null && typeof args[key] === 'object'){
rdformatterAssign(args[key],formatter)
}else if(key === 'format' && typeof args[key] === 'string'){
args['formatter'] = formatter[args[key]] ? formatter[args[key]] : undefined;
}
}
return args;
}
export default {
data() {
return {
rid:null
}
},
mounted() {
rootdom = {top:0,left:0}
// #ifdef H5
let dm = document.querySelectorAll('uni-main')[0]
if(dm === undefined){
dm = document.querySelectorAll('uni-page-wrapper')[0]
}
rootdom = {top:dm.offsetTop,left:dm.offsetLeft}
// #endif
setTimeout(()=>{
if(this.rid === null){
this.$ownerInstance.callMethod('getRenderType')
}
},200)
},
destroyed(){
delete cfu.option[this.rid]
delete cfu.instance[this.rid]
delete cfe.option[this.rid]
delete cfe.instance[this.rid]
},
methods: {
//==============以下是ECharts的方法====================
ecinit(newVal, oldVal, owner, instance){
let cid = JSON.stringify(newVal.id)
this.rid = cid
that[cid] = this.$ownerInstance
let eopts = JSON.parse(JSON.stringify(newVal))
let type = eopts.type;
//载入并覆盖默认配置
if (type && cfe.type.includes(type)) {
cfe.option[cid] = rddeepCloneAssign({}, cfe[type], eopts);
}else{
cfe.option[cid] = rddeepCloneAssign({}, eopts);
}
let newData = eopts.chartData;
if(newData){
//挂载categories和series
if(cfe.option[cid].xAxis && cfe.option[cid].xAxis.type && cfe.option[cid].xAxis.type === 'category'){
cfe.option[cid].xAxis.data = newData.categories
}
if(cfe.option[cid].yAxis && cfe.option[cid].yAxis.type && cfe.option[cid].yAxis.type === 'category'){
cfe.option[cid].yAxis.data = newData.categories
}
cfe.option[cid].series = []
for (var i = 0; i < newData.series.length; i++) {
cfe.option[cid].seriesTemplate = cfe.option[cid].seriesTemplate ? cfe.option[cid].seriesTemplate : {}
let Template = rddeepCloneAssign({},cfe.option[cid].seriesTemplate,newData.series[i])
cfe.option[cid].series.push(Template)
}
}
if (typeof window.echarts === 'object') {
this.newEChart()
}else{
const script = document.createElement('script')
// #ifdef APP-VUE
script.src = './static/app-plus/echarts.min.js';
// #endif
// #ifdef H5
const { origin } = window.location;
let base_url = "";
// #ifdef VUE2
base_url = process.env.BASE_URL;
// #endif
// #ifdef VUE3
base_url = import.meta.env.BASE_URL;
// #endif
const rooturl = origin + base_url;
script.src = rooturl + 'static/h5/echarts.min.js';
// #endif
script.onload = this.newEChart
document.head.appendChild(script)
}
},
ecresize(newVal, oldVal, owner, instance){
if(cfe.instance[this.rid]){
cfe.instance[this.rid].resize()
}
},
newEChart(){
let cid = this.rid
if(cfe.instance[cid] === undefined){
cfe.instance[cid] = echarts.init(that[cid].$el.children[0])
//ontap开启后才触发click事件
if(cfe.option[cid].ontap === true){
cfe.instance[cid].on('click', resdata => {
let event = JSON.parse(JSON.stringify({
x:resdata.event.offsetX,y:resdata.event.offsetY
}))
that[cid].callMethod('emitMsg',{name:"getIndex", params:{type:"getIndex", event:event, currentIndex:resdata.dataIndex, value:resdata.data, seriesName: resdata.seriesName,id:cid}})
})
// 增加ECharts的highlight消息,实现按下移动返回索引功能。add by onefish 创建于 2021-12-11 09:50
cfe.instance[cid].on('highlight', resdata => {
that[cid].callMethod('emitMsg',{name:"getHighlight", params:{type:"highlight", res:resdata, id:cid}})
})
}
this.updataEChart(cid,cfe.option[cid])
}else{
this.updataEChart(cid,cfe.option[cid])
}
},
updataEChart(cid,option){
//替换option内format属性为formatter的预定义方法
option = rdformatterAssign(option,cfe.formatter)
if(option.tooltip){
option.tooltip.show = option.tooltipShow?true:false;
option.tooltip.position = this.tooltipPosition()
//tooltipFormat方法,替换组件的tooltipFormat为config-echarts.js内对应的方法
if (typeof option.tooltipFormat === 'string' && cfe.formatter[option.tooltipFormat]) {
option.tooltip.formatter = option.tooltip.formatter ? option.tooltip.formatter : cfe.formatter[option.tooltipFormat]
}
}
// 颜色渐变添加的方法
if (option.series) {
for (let i in option.series) {
let linearGradient = option.series[i].linearGradient
if (linearGradient) {
option.series[i].color = new echarts.graphic.LinearGradient(linearGradient[0],linearGradient[1],linearGradient[2],linearGradient[3],linearGradient[4])
}
}
}
cfe.instance[cid].setOption(option, option.notMerge)
cfe.instance[cid].on('finished', function(){
that[cid].callMethod('emitMsg',{name:"complete",params:{type:"complete",complete:true,id:cid}})
if(cfe.instance[cid]){
cfe.instance[cid].off('finished')
}
});
//修复init初始化实例获取宽高不正确问题
if(
typeof that[cid].$el.children[0].clientWidth != 'undefined' &&
(
Math.abs( that[cid].$el.children[0].clientWidth - cfe.instance[cid].getWidth() )>3 ||
Math.abs( that[cid].$el.children[0].clientHeight - cfe.instance[cid].getHeight() )>3
)
){this.ecresize();}
},
tooltipPosition(){
return (point, params, dom, rect, size) => {
let x = point[0]
let y = point[1]
let viewWidth = size.viewSize[0]
let viewHeight = size.viewSize[1]
let boxWidth = size.contentSize[0]
let boxHeight = size.contentSize[1]
let posX = x + 30
let posY = y + 30
if (posX + boxWidth > viewWidth) {
posX = x - boxWidth - 30
}
if (posY + boxHeight > viewHeight) {
posY = y - boxHeight - 30
}
return [posX, posY]
}
},
//==============以下是uCharts的方法====================
ucinit(newVal, oldVal, owner, instance){
if(JSON.stringify(newVal) == JSON.stringify(oldVal)){
return;
}
if(!newVal.canvasId){
return;
}
let cid = JSON.parse(JSON.stringify(newVal.canvasId))
this.rid = cid
that[cid] = this.$ownerInstance
cfu.option[cid] = JSON.parse(JSON.stringify(newVal))
cfu.option[cid] = rdformatterAssign(cfu.option[cid],cfu.formatter)
let canvasdom = document.getElementById(cid)
if(canvasdom && canvasdom.children[0]){
cfu.option[cid].context = canvasdom.children[0].getContext("2d")
if(cfu.instance[cid] && cfu.option[cid] && cfu.option[cid].update === true){
this.updataUChart()
}else{
setTimeout(()=>{
cfu.option[cid].context.restore();
cfu.option[cid].context.save();
this.newUChart()
},100)
}
}
},
newUChart() {
let cid = this.rid
cfu.instance[cid] = new uChartsRD(cfu.option[cid])
cfu.instance[cid].addEventListener('renderComplete', () => {
that[cid].callMethod('emitMsg',{name:"complete",params:{type:"complete",complete:true,id:cid, opts: cfu.instance[cid].opts}})
cfu.instance[cid].delEventListener('renderComplete')
});
cfu.instance[cid].addEventListener('scrollLeft', () => {
that[cid].callMethod('emitMsg',{name:"scrollLeft",params:{type:"scrollLeft",scrollLeft:true,id:cid, opts: cfu.instance[cid].opts}})
});
cfu.instance[cid].addEventListener('scrollRight', () => {
that[cid].callMethod('emitMsg',{name:"scrollRight",params:{type:"scrollRight",scrollRight:true,id:cid, opts: cfu.instance[cid].opts}})
});
},
updataUChart() {
let cid = this.rid
cfu.instance[cid].updateData(cfu.option[cid])
},
tooltipDefault(item, category, index, opts) {
if (category) {
let data = item.data
if(typeof item.data === "object"){
data = item.data.value
}
return category + ' ' + item.name + ':' + data;
} else {
if (item.properties && item.properties.name) {
return item.properties.name;
} else {
return item.name + ':' + item.data;
}
}
},
showTooltip(e,cid) {
let tc = cfu.option[cid].tooltipCustom
if (tc && tc !== undefined && tc !== null) {
let offset = undefined;
if (tc.x >= 0 && tc.y >= 0) {
offset = { x: tc.x, y: tc.y + 10 };
}
cfu.instance[cid].showToolTip(e, {
index: tc.index,
offset: offset,
textList: tc.textList,
formatter: (item, category, index, opts) => {
if (typeof cfu.option[cid].tooltipFormat === 'string' && cfu.formatter[cfu.option[cid].tooltipFormat]) {
return cfu.formatter[cfu.option[cid].tooltipFormat](item, category, index, opts);
} else {
return this.tooltipDefault(item, category, index, opts);
}
}
});
} else {
cfu.instance[cid].showToolTip(e, {
formatter: (item, category, index, opts) => {
if (typeof cfu.option[cid].tooltipFormat === 'string' && cfu.formatter[cfu.option[cid].tooltipFormat]) {
return cfu.formatter[cfu.option[cid].tooltipFormat](item, category, index, opts);
} else {
return this.tooltipDefault(item, category, index, opts);
}
}
});
}
},
tap(e) {
let cid = this.rid
let ontap = cfu.option[cid].ontap
let tooltipShow = cfu.option[cid].tooltipShow
let tapLegend = cfu.option[cid].tapLegend
if(ontap == false) return;
let currentIndex=null
let legendIndex=null
let rchartdom = document.getElementById('UC'+cid).getBoundingClientRect()
let tmpe = {}
if(e.detail.x){//tap或者click的事件
tmpe = { x: e.detail.x - rchartdom.left, y:e.detail.y - rchartdom.top + rootdom.top}
}else{//mouse的事件
tmpe = { x: e.clientX - rchartdom.left, y:e.clientY - rchartdom.top + rootdom.top}
}
e.changedTouches.unshift(tmpe)
currentIndex=cfu.instance[cid].getCurrentDataIndex(e)
legendIndex=cfu.instance[cid].getLegendDataIndex(e)
if(tapLegend === true){
cfu.instance[cid].touchLegend(e);
}
if(tooltipShow==true){
this.showTooltip(e,cid)
}
that[cid].callMethod('emitMsg',{name:"getIndex",params:{type:"getIndex",event:tmpe,currentIndex:currentIndex,legendIndex:legendIndex,id:cid, opts: cfu.instance[cid].opts}})
},
touchStart(e) {
let cid = this.rid
let ontouch = cfu.option[cid].ontouch
if(ontouch == false) return;
if(cfu.option[cid].enableScroll === true && e.touches.length == 1){
cfu.instance[cid].scrollStart(e);
}
that[cid].callMethod('emitMsg',{name:"getTouchStart",params:{type:"touchStart",event:e.changedTouches[0],id:cid, opts: cfu.instance[cid].opts}})
},
touchMove(e) {
let cid = this.rid
let ontouch = cfu.option[cid].ontouch
if(ontouch == false) return;
if(cfu.option[cid].enableScroll === true && e.changedTouches.length == 1){
cfu.instance[cid].scroll(e);
}
if(cfu.option[cid].ontap === true && cfu.option[cid].enableScroll === false && cfu.option[cid].onmovetip === true){
let rchartdom = document.getElementById('UC'+cid).getBoundingClientRect()
let tmpe = { x: e.changedTouches[0].clientX - rchartdom.left, y:e.changedTouches[0].clientY - rchartdom.top + rootdom.top}
e.changedTouches.unshift(tmpe)
if(cfu.option[cid].tooltipShow === true){
this.showTooltip(e,cid)
}
}
if(ontouch === true && cfu.option[cid].enableScroll === true && cfu.option[cid].onzoom === true && e.changedTouches.length == 2){
cfu.instance[cid].dobuleZoom(e);
}
that[cid].callMethod('emitMsg',{name:"getTouchMove",params:{type:"touchMove",event:e.changedTouches[0],id:cid, opts: cfu.instance[cid].opts}})
},
touchEnd(e) {
let cid = this.rid
let ontouch = cfu.option[cid].ontouch
if(ontouch == false) return;
if(cfu.option[cid].enableScroll === true && e.touches.length == 0){
cfu.instance[cid].scrollEnd(e);
}
that[cid].callMethod('emitMsg',{name:"getTouchEnd",params:{type:"touchEnd",event:e.changedTouches[0],id:cid, opts: cfu.instance[cid].opts}})
},
mouseDown(e) {
let cid = this.rid
let onmouse = cfu.option[cid].onmouse
if(onmouse == false) return;
let rchartdom = document.getElementById('UC'+cid).getBoundingClientRect()
let tmpe = {}
tmpe = { x: e.clientX - rchartdom.left, y:e.clientY - rchartdom.top + rootdom.top}
e.changedTouches.unshift(tmpe)
cfu.instance[cid].scrollStart(e)
cfu.option[cid].mousedown=true;
that[cid].callMethod('emitMsg',{name:"getTouchStart",params:{type:"mouseDown",event:tmpe,id:cid, opts: cfu.instance[cid].opts}})
},
mouseMove(e) {
let cid = this.rid
let onmouse = cfu.option[cid].onmouse
let tooltipShow = cfu.option[cid].tooltipShow
if(onmouse == false) return;
let rchartdom = document.getElementById('UC'+cid).getBoundingClientRect()
let tmpe = {}
tmpe = { x: e.clientX - rchartdom.left, y:e.clientY - rchartdom.top + rootdom.top}
e.changedTouches.unshift(tmpe)
if(cfu.option[cid].mousedown){
cfu.instance[cid].scroll(e)
that[cid].callMethod('emitMsg',{name:"getTouchMove",params:{type:"mouseMove",event:tmpe,id:cid, opts: cfu.instance[cid].opts}})
}else if(cfu.instance[cid]){
if(tooltipShow==true){
this.showTooltip(e,cid)
}
}
},
mouseUp(e) {
let cid = this.rid
let onmouse = cfu.option[cid].onmouse
if(onmouse == false) return;
let rchartdom = document.getElementById('UC'+cid).getBoundingClientRect()
let tmpe = {}
tmpe = { x: e.clientX - rchartdom.left, y:e.clientY - rchartdom.top + rootdom.top}
e.changedTouches.unshift(tmpe)
cfu.instance[cid].scrollEnd(e)
cfu.option[cid].mousedown=false;
that[cid].callMethod('emitMsg',{name:"getTouchEnd",params:{type:"mouseUp",event:tmpe,id:cid, opts: cfu.instance[cid].opts}})
},
}
}
</script>
<!-- #endif -->
<style scoped>
.chartsview {
display: flex;
flex: 1;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
</style>
align-items: center; wdh100%; high: 100%
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
<template>
<view class="chartsview">
<view class="charts-error"></view>
<view class="charts-font">{{ errorMessage == null ? '请点击重试' : errorMessage }}</view>
</view>
</template>
<script>
export default {
name: 'qiun-error',
props: {
errorMessage: {
type: String,
default: null,
},
},
data() {
return {}
},
}
</script>
<style>
.chartsview {
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.charts-font {
margin-top: 10px;
font-size: 14px;
color: #ccc;
}
.charts-error {
width: 128px;
height: 128px;
background: url('data:image/png;base64,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');
background-position: center;
}
</style>
<template>
<view class="container loading1">
<view class="shape shape1"></view>
<view class="shape shape2"></view>
<view class="shape shape3"></view>
<view class="shape shape4"></view>
</view>
</template>
<script>
export default {
name: 'loading1',
data() {
return {}
},
}
</script>
<style scoped="true">
.container {
position: relative;
width: 30px;
height: 30px;
}
.container.loading1 {
transform: rotate(45deg);
}
.container .shape {
position: absolute;
width: 10px;
height: 10px;
border-radius: 1px;
}
.container .shape.shape1 {
left: 0;
background-color: #1890ff;
}
.container .shape.shape2 {
right: 0;
background-color: #91cb74;
}
.container .shape.shape3 {
bottom: 0;
background-color: #fac858;
}
.container .shape.shape4 {
right: 0;
bottom: 0;
background-color: #e66;
}
.loading1 .shape1 {
animation: animation1shape1 0.5s ease 0s infinite alternate;
}
@keyframes animation1shape1 {
from {
transform: translate(0, 0);
}
to {
transform: translate(16px, 16px);
}
}
@keyframes animation1shape1 {
from {
transform: translate(0, 0);
}
to {
transform: translate(16px, 16px);
}
}
.loading1 .shape2 {
animation: animation1shape2 0.5s ease 0s infinite alternate;
}
@keyframes animation1shape2 {
from {
transform: translate(0, 0);
}
to {
transform: translate(-16px, 16px);
}
}
@keyframes animation1shape2 {
from {
transform: translate(0, 0);
}
to {
transform: translate(-16px, 16px);
}
}
.loading1 .shape3 {
animation: animation1shape3 0.5s ease 0s infinite alternate;
}
@keyframes animation1shape3 {
from {
transform: translate(0, 0);
}
to {
transform: translate(16px, -16px);
}
}
@keyframes animation1shape3 {
from {
transform: translate(0, 0);
}
to {
transform: translate(16px, -16px);
}
}
.loading1 .shape4 {
animation: animation1shape4 0.5s ease 0s infinite alternate;
}
@keyframes animation1shape4 {
from {
transform: translate(0, 0);
}
to {
transform: translate(-16px, -16px);
}
}
@keyframes animation1shape4 {
from {
transform: translate(0, 0);
}
to {
transform: translate(-16px, -16px);
}
}
</style>
<template>
<view class="container loading2">
<view class="shape shape1"></view>
<view class="shape shape2"></view>
<view class="shape shape3"></view>
<view class="shape shape4"></view>
</view>
</template>
<script>
export default {
name: 'loading2',
data() {
return {}
},
}
</script>
<style scoped="true">
.container {
position: relative;
width: 30px;
height: 30px;
}
.container.loading2 {
transform: rotate(10deg);
transform: rotate(10deg);
}
.container.loading2 .shape {
border-radius: 5px;
}
.container.loading2 {
animation: rotation 1s infinite;
animation: rotation 1s infinite;
}
.container .shape {
position: absolute;
width: 10px;
height: 10px;
border-radius: 1px;
}
.container .shape.shape1 {
left: 0;
background-color: #1890ff;
}
.container .shape.shape2 {
right: 0;
background-color: #91cb74;
}
.container .shape.shape3 {
bottom: 0;
background-color: #fac858;
}
.container .shape.shape4 {
right: 0;
bottom: 0;
background-color: #e66;
}
.loading2 .shape1 {
animation: animation2shape1 0.5s ease 0s infinite alternate;
animation: animation2shape1 0.5s ease 0s infinite alternate;
}
@keyframes animation2shape1 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(20px, 20px);
transform: translate(20px, 20px);
}
}
@keyframes animation2shape1 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(20px, 20px);
transform: translate(20px, 20px);
}
}
.loading2 .shape2 {
animation: animation2shape2 0.5s ease 0s infinite alternate;
animation: animation2shape2 0.5s ease 0s infinite alternate;
}
@keyframes animation2shape2 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-20px, 20px);
transform: translate(-20px, 20px);
}
}
@keyframes animation2shape2 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-20px, 20px);
transform: translate(-20px, 20px);
}
}
.loading2 .shape3 {
animation: animation2shape3 0.5s ease 0s infinite alternate;
animation: animation2shape3 0.5s ease 0s infinite alternate;
}
@keyframes animation2shape3 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(20px, -20px);
transform: translate(20px, -20px);
}
}
@keyframes animation2shape3 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(20px, -20px);
transform: translate(20px, -20px);
}
}
.loading2 .shape4 {
animation: animation2shape4 0.5s ease 0s infinite alternate;
animation: animation2shape4 0.5s ease 0s infinite alternate;
}
@keyframes animation2shape4 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-20px, -20px);
transform: translate(-20px, -20px);
}
}
@keyframes animation2shape4 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-20px, -20px);
transform: translate(-20px, -20px);
}
}
</style>
<template>
<view class="container loading3">
<view class="shape shape1"></view>
<view class="shape shape2"></view>
<view class="shape shape3"></view>
<view class="shape shape4"></view>
</view>
</template>
<script>
export default {
name: 'loading3',
data() {
return {}
},
}
</script>
<style scoped="true">
.container {
position: relative;
width: 30px;
height: 30px;
}
.container.loading3 {
animation: rotation 1s infinite;
animation: rotation 1s infinite;
}
.container.loading3 .shape1 {
border-top-left-radius: 10px;
}
.container.loading3 .shape2 {
border-top-right-radius: 10px;
}
.container.loading3 .shape3 {
border-bottom-left-radius: 10px;
}
.container.loading3 .shape4 {
border-bottom-right-radius: 10px;
}
.container .shape {
position: absolute;
width: 10px;
height: 10px;
border-radius: 1px;
}
.container .shape.shape1 {
left: 0;
background-color: #1890ff;
}
.container .shape.shape2 {
right: 0;
background-color: #91cb74;
}
.container .shape.shape3 {
bottom: 0;
background-color: #fac858;
}
.container .shape.shape4 {
right: 0;
bottom: 0;
background-color: #e66;
}
.loading3 .shape1 {
animation: animation3shape1 0.5s ease 0s infinite alternate;
animation: animation3shape1 0.5s ease 0s infinite alternate;
}
@keyframes animation3shape1 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(5px, 5px);
transform: translate(5px, 5px);
}
}
@keyframes animation3shape1 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(5px, 5px);
transform: translate(5px, 5px);
}
}
.loading3 .shape2 {
animation: animation3shape2 0.5s ease 0s infinite alternate;
animation: animation3shape2 0.5s ease 0s infinite alternate;
}
@keyframes animation3shape2 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-5px, 5px);
transform: translate(-5px, 5px);
}
}
@keyframes animation3shape2 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-5px, 5px);
transform: translate(-5px, 5px);
}
}
.loading3 .shape3 {
animation: animation3shape3 0.5s ease 0s infinite alternate;
animation: animation3shape3 0.5s ease 0s infinite alternate;
}
@keyframes animation3shape3 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(5px, -5px);
transform: translate(5px, -5px);
}
}
@keyframes animation3shape3 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(5px, -5px);
transform: translate(5px, -5px);
}
}
.loading3 .shape4 {
animation: animation3shape4 0.5s ease 0s infinite alternate;
animation: animation3shape4 0.5s ease 0s infinite alternate;
}
@keyframes animation3shape4 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-5px, -5px);
transform: translate(-5px, -5px);
}
}
@keyframes animation3shape4 {
from {
transform: translate(0, 0);
transform: translate(0, 0);
}
to {
transform: translate(-5px, -5px);
transform: translate(-5px, -5px);
}
}
</style>
<template>
<view class="container loading5">
<view class="shape shape1"></view>
<view class="shape shape2"></view>
<view class="shape shape3"></view>
<view class="shape shape4"></view>
</view>
</template>
<script>
export default {
name: 'loading5',
data() {
return {}
},
}
</script>
<style scoped="true">
.container {
position: relative;
width: 30px;
height: 30px;
}
.container.loading5 .shape {
width: 15px;
height: 15px;
}
.container .shape {
position: absolute;
width: 10px;
height: 10px;
border-radius: 1px;
}
.container .shape.shape1 {
left: 0;
background-color: #1890ff;
}
.container .shape.shape2 {
right: 0;
background-color: #91cb74;
}
.container .shape.shape3 {
bottom: 0;
background-color: #fac858;
}
.container .shape.shape4 {
right: 0;
bottom: 0;
background-color: #e66;
}
.loading5 .shape1 {
animation: animation5shape1 2s ease 0s infinite reverse;
}
@keyframes animation5shape1 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, 15px);
transform: translate(0, 15px);
}
50% {
transform: translate(15px, 15px);
transform: translate(15px, 15px);
}
75% {
transform: translate(15px, 0);
transform: translate(15px, 0);
}
}
@keyframes animation5shape1 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, 15px);
transform: translate(0, 15px);
}
50% {
transform: translate(15px, 15px);
transform: translate(15px, 15px);
}
75% {
transform: translate(15px, 0);
transform: translate(15px, 0);
}
}
.loading5 .shape2 {
animation: animation5shape2 2s ease 0s infinite reverse;
}
@keyframes animation5shape2 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(-15px, 0);
transform: translate(-15px, 0);
}
50% {
transform: translate(-15px, 15px);
transform: translate(-15px, 15px);
}
75% {
transform: translate(0, 15px);
transform: translate(0, 15px);
}
}
@keyframes animation5shape2 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(-15px, 0);
transform: translate(-15px, 0);
}
50% {
transform: translate(-15px, 15px);
transform: translate(-15px, 15px);
}
75% {
transform: translate(0, 15px);
transform: translate(0, 15px);
}
}
.loading5 .shape3 {
animation: animation5shape3 2s ease 0s infinite reverse;
}
@keyframes animation5shape3 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(15px, 0);
transform: translate(15px, 0);
}
50% {
transform: translate(15px, -15px);
transform: translate(15px, -15px);
}
75% {
transform: translate(0, -15px);
transform: translate(0, -15px);
}
}
@keyframes animation5shape3 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(15px, 0);
transform: translate(15px, 0);
}
50% {
transform: translate(15px, -15px);
transform: translate(15px, -15px);
}
75% {
transform: translate(0, -15px);
transform: translate(0, -15px);
}
}
.loading5 .shape4 {
animation: animation5shape4 2s ease 0s infinite reverse;
}
@keyframes animation5shape4 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, -15px);
transform: translate(0, -15px);
}
50% {
transform: translate(-15px, -15px);
transform: translate(-15px, -15px);
}
75% {
transform: translate(-15px, 0);
transform: translate(-15px, 0);
}
}
@keyframes animation5shape4 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, -15px);
transform: translate(0, -15px);
}
50% {
transform: translate(-15px, -15px);
transform: translate(-15px, -15px);
}
75% {
transform: translate(-15px, 0);
transform: translate(-15px, 0);
}
}
</style>
<template>
<view class="container loading6">
<view class="shape shape1"></view>
<view class="shape shape2"></view>
<view class="shape shape3"></view>
<view class="shape shape4"></view>
</view>
</template>
<script>
export default {
name: 'loading6',
data() {
return {}
},
}
</script>
<style scoped="true">
.container {
position: relative;
width: 30px;
height: 30px;
}
.container.loading6 {
animation: rotation 1s infinite;
animation: rotation 1s infinite;
}
.container.loading6 .shape {
width: 12px;
height: 12px;
border-radius: 2px;
}
.container .shape {
position: absolute;
width: 10px;
height: 10px;
border-radius: 1px;
}
.container .shape.shape1 {
left: 0;
background-color: #1890ff;
}
.container .shape.shape2 {
right: 0;
background-color: #91cb74;
}
.container .shape.shape3 {
bottom: 0;
background-color: #fac858;
}
.container .shape.shape4 {
right: 0;
bottom: 0;
background-color: #e66;
}
.loading6 .shape1 {
animation: animation6shape1 2s linear 0s infinite normal;
animation: animation6shape1 2s linear 0s infinite normal;
}
@keyframes animation6shape1 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, 18px);
transform: translate(0, 18px);
}
50% {
transform: translate(18px, 18px);
transform: translate(18px, 18px);
}
75% {
transform: translate(18px, 0);
transform: translate(18px, 0);
}
}
@keyframes animation6shape1 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, 18px);
transform: translate(0, 18px);
}
50% {
transform: translate(18px, 18px);
transform: translate(18px, 18px);
}
75% {
transform: translate(18px, 0);
transform: translate(18px, 0);
}
}
.loading6 .shape2 {
animation: animation6shape2 2s linear 0s infinite normal;
animation: animation6shape2 2s linear 0s infinite normal;
}
@keyframes animation6shape2 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(-18px, 0);
transform: translate(-18px, 0);
}
50% {
transform: translate(-18px, 18px);
transform: translate(-18px, 18px);
}
75% {
transform: translate(0, 18px);
transform: translate(0, 18px);
}
}
@keyframes animation6shape2 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(-18px, 0);
transform: translate(-18px, 0);
}
50% {
transform: translate(-18px, 18px);
transform: translate(-18px, 18px);
}
75% {
transform: translate(0, 18px);
transform: translate(0, 18px);
}
}
.loading6 .shape3 {
animation: animation6shape3 2s linear 0s infinite normal;
animation: animation6shape3 2s linear 0s infinite normal;
}
@keyframes animation6shape3 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(18px, 0);
transform: translate(18px, 0);
}
50% {
transform: translate(18px, -18px);
transform: translate(18px, -18px);
}
75% {
transform: translate(0, -18px);
transform: translate(0, -18px);
}
}
@keyframes animation6shape3 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(18px, 0);
transform: translate(18px, 0);
}
50% {
transform: translate(18px, -18px);
transform: translate(18px, -18px);
}
75% {
transform: translate(0, -18px);
transform: translate(0, -18px);
}
}
.loading6 .shape4 {
animation: animation6shape4 2s linear 0s infinite normal;
animation: animation6shape4 2s linear 0s infinite normal;
}
@keyframes animation6shape4 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, -18px);
transform: translate(0, -18px);
}
50% {
transform: translate(-18px, -18px);
transform: translate(-18px, -18px);
}
75% {
transform: translate(-18px, 0);
transform: translate(-18px, 0);
}
}
@keyframes animation6shape4 {
0% {
transform: translate(0, 0);
transform: translate(0, 0);
}
25% {
transform: translate(0, -18px);
transform: translate(0, -18px);
}
50% {
transform: translate(-18px, -18px);
transform: translate(-18px, -18px);
}
75% {
transform: translate(-18px, 0);
transform: translate(-18px, 0);
}
}
</style>
<template>
<view>
<Loading1 v-if="loadingType == 1" />
<Loading2 v-if="loadingType == 2" />
<Loading3 v-if="loadingType == 3" />
<Loading4 v-if="loadingType == 4" />
<Loading5 v-if="loadingType == 5" />
</view>
</template>
<script>
import Loading1 from './loading1.vue'
import Loading2 from './loading2.vue'
import Loading3 from './loading3.vue'
import Loading4 from './loading4.vue'
import Loading5 from './loading5.vue'
export default {
components: { Loading1, Loading2, Loading3, Loading4, Loading5 },
name: 'qiun-loading',
props: {
loadingType: {
type: Number,
default: 2,
},
},
data() {
return {}
},
}
</script>
<style></style>
<template>
<view class="qiun-title-bar">
<view class="qiun-title-dot"></view>
<view class="qiun-title-text">{{ title }}</view>
</view>
</template>
<script>
export default {
name: 'title-bar',
props: {
title: {
type: String,
default: '',
},
},
mounted() {},
methods: {},
}
</script>
<style>
.qiun-title-bar {
display: flex;
flex-direction: row !important;
flex-wrap: nowrap;
align-items: center;
height: 40px;
}
.qiun-title-dot {
width: 5px;
height: 16px;
margin-left: 8px;
background-color: #409eff;
border-radius: 10px;
}
.qiun-title-text {
height: 22px;
margin-left: 8px;
font-size: 17px;
font-weight: bold;
line-height: 22px;
color: #666;
}
</style>
/// <reference types="vite/client" />
/// <reference types="vite-svg-loader" />
declare module '*.vue' {
import { DefineComponent } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}
interface ImportMetaEnv {
readonly VITE_APP_TITLE: string
readonly VITE_SERVER_PORT: string
readonly VITE_SERVER_BASEURL: string
readonly VITE_DELETE_CONSOLE: string
// 更多环境变量...
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
/* eslint-disable import/first */
// 小程序中引入 echarts
// #ifndef APP-PLUS || H5
// eslint-disable-next-line @typescript-eslint/no-var-requires
const echarts = require('../uni_modules/lime-echart/static/echarts.min')
// #endif
// APP 与 H5 引入 echarts
// #ifdef APP-PLUS || H5
import * as echartsAppOrH5 from 'echarts'
// #endif
import { ref } from 'vue'
// echarts 图表 Hooks
export const useEcharts = (options): any => {
// echarts 图实例
const chartRef = ref(null)
// echarts 图绘制函数
const draw = () => {
setTimeout(async () => {
if (!chartRef.value) return
// #ifndef APP-PLUS || H5
const chart = await chartRef.value.init(echarts)
chart.setOption(options.value)
// #endif
// #ifdef APP-PLUS || H5
const chartAPP = await chartRef.value.init(echartsAppOrH5)
chartAPP.setOption(options.value)
// #endif
}, 300)
}
// 这里就封装巧妙之处,如果是对象,那么需要重命名,而是是数组,无需重命名
return [chartRef, options, draw]
}
import { onReady } from '@dcloudio/uni-app'
import { getIsTabbar, getLastItem } from '@/utils/index'
export default () => {
// 获取页面栈
const pages = getCurrentPages()
const isTabbar = getIsTabbar()
// 页面滚动到底部时的操作,通常用于加载更多数据
const onScrollToLower = () => {}
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// #ifdef MP-WEIXIN
// 基于小程序的 Page 类型扩展 uni-app 的 Page
type PageInstance = Page.PageInstance & WechatMiniprogram.Page.InstanceMethods<any>
// 获取当前页面实例,数组最后一项
const pageInstance = getLastItem(getCurrentPages()) as PageInstance
// 页面渲染完毕,绑定动画效果
onReady(() => {
// 动画效果,导航栏背景色
pageInstance.animate(
'.fly-navbar',
[{ backgroundColor: 'transparent' }, { backgroundColor: '#f8f8f8' }],
1000,
{
scrollSource: '#scroller',
timeRange: 1000,
startScrollOffset: 0,
endScrollOffset: 50,
},
)
// 动画效果,导航栏标题
pageInstance.animate(
'.fly-navbar .title',
[{ color: 'transparent' }, { color: '#000' }],
1000,
{
scrollSource: '#scroller',
timeRange: 1000,
startScrollOffset: 0,
endScrollOffset: 50,
},
)
// 动画效果,导航栏返回按钮
pageInstance.animate('.fly-navbar .left-icon', [{ color: '#fff' }, { color: '#000' }], 1000, {
scrollSource: '#scroller',
timeRange: 1000,
startScrollOffset: 0,
endScrollOffset: 50,
})
})
// #endif
return {
pages,
isTabbar,
onScrollToLower,
safeAreaInsets,
}
}
import { UnwrapRef } from 'vue'
type IUseRequestOptions<T> = {
/** 是否立即执行,如果是则在onLoad执行 */
immediate?: boolean
/** 初始化数据 */
initialData?: T
}
/**
* useRequest是一个定制化的请求钩子,用于处理异步请求和响应。
* @param func 一个执行异步请求的函数,返回一个包含响应数据的Promise。
* @param options 包含请求选项的对象 {immediate, initialData}。
* @param options.immediate 是否立即执行请求,默认为true。
* @param options.initialData 初始化数据,默认为undefined。
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
*/
export default function useRequest<T>(
func: () => Promise<IResData<T>>,
options: IUseRequestOptions<T> = { immediate: true },
) {
const loading = ref(false)
const error = ref(false)
const data = ref<T>(options.initialData)
const run = async () => {
loading.value = true
func()
.then((res) => {
data.value = res.data as UnwrapRef<T>
error.value = false
})
.catch((err) => {
error.value = err
})
.finally(() => {
loading.value = false
})
}
onLoad(() => {
options.immediate && run()
})
return { loading, error, data, run }
}
// TODO: 别忘加更改环境变量的 VITE_UPLOAD_BASEURL 地址。
const VITE_UPLOAD_BASEURL = import.meta.env.VITE_UPLOAD_BASEURL
/**
* useUpload 是一个定制化的请求钩子,用于处理上传图片。
* @param formData 额外传递给后台的数据,如{name: '菲鸽'}。
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
*/
export default function useUpload<T = string>(formData: Record<string, any> = {}) {
const loading = ref(false)
const error = ref(false)
const data = ref<T>()
const run = () => {
// #ifdef MP-WEIXIN
// 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
// 微信小程序在2023年10月17日之后,使用本API需要配置隐私协议
uni.chooseMedia({
count: 1,
mediaType: ['image'],
success: (res) => {
loading.value = true
const tempFilePath = res.tempFiles[0].tempFilePath
uploadFile<T>({ tempFilePath, formData, data, error, loading })
},
fail: (err) => {
console.log('uni.chooseMedia err->', err)
error.value = true
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseImage({
count: 1,
success: (res) => {
loading.value = true
const tempFilePath = res.tempFilePaths[0]
uploadFile<T>({ tempFilePath, formData, data, error, loading })
},
fail: (err) => {
console.log('uni.chooseImage err->', err)
error.value = true
},
})
// #endif
}
return { loading, error, data, run }
}
function uploadFile<T>({ tempFilePath, formData, data, error, loading }) {
uni.uploadFile({
url: VITE_UPLOAD_BASEURL,
filePath: tempFilePath,
name: 'file',
formData,
success: (uploadFileRes) => {
data.value = uploadFileRes.data as T
},
fail: (err) => {
console.log('uni.uploadFile err->', err)
error.value = true
},
complete: () => {
loading.value = false
},
})
}
/* eslint-disable no-unused-vars */
export {}
declare module 'vue' {
interface ComponentCustomProperties {
$t: (key: string, opt?: Record<string, any>) => string
$tm: (key: string, opt?: Record<string, any>) => [] | { [p: string]: any }
}
}
export { routeInterceptor } from './route'
export { requestInterceptor } from './request'
/* eslint-disable no-param-reassign */
import qs from 'qs'
import { useUserStore } from '@/store'
export type CustomRequestOptions = UniApp.RequestOptions & {
query?: Record<string, any>
} & IUniUploadFileOptions // 添加uni.uploadFile参数类型
// 请求基地址
const baseURL = import.meta.env.VITE_SERVER_BASEURL
// 拦截器配置
const httpInterceptor = {
// 拦截前触发
invoke(options: CustomRequestOptions) {
// 接口请求支持通过 query 参数配置 queryString
if (options.query) {
const queryStr = qs.stringify(options.query)
if (options.url.includes('?')) {
options.url += `&${queryStr}`
} else {
options.url += `?${queryStr}`
}
}
// api 目前为 mock 接口,所以无需处理
if (!options.url.startsWith('http')) {
// 1. 非 http 开头需拼接地址
options.url = baseURL + options.url
}
// 2. 请求超时
options.timeout = 10000 // 10s
// 3. 添加小程序端请求头标识
options.header = {
platform: 'mp-weixin', // 可选值与 uniapp 定义的平台一致,告诉后台来源
...options.header,
}
// 4. 添加 token 请求头标识
const userStore = useUserStore()
const { token } = userStore.userInfo as unknown as IUserInfo
if (token) {
options.header.Authorization = `Bearer ${token}`
}
},
}
export const requestInterceptor = {
install() {
// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)
},
}
/**
* by 菲鸽 on 2024-03-06
* 路由拦截,通常也是登录拦截
* 可以设置路由白名单,或者黑名单,看业务需要选哪一个
* 我这里应为大部分都可以随便进入,所以使用黑名单
*/
import { useUserStore } from '@/store'
import { getNeedLoginPages, needLoginPages as _needLoginPages } from '@/utils'
// TODO Check
const loginRoute = '/pages/login/index'
const isLogined = () => {
const userStore = useUserStore()
return userStore.isLogined
}
const isDev = import.meta.env.DEV
// 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
const navigateToInterceptor = {
// 注意,这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
invoke({ url }: { url: string }) {
console.log(url) // /pages/route-interceptor/index?name=feige&age=30
const path = url.split('?')[0]
let needLoginPages: string[] = []
// 为了防止开发时出现BUG,这里每次都获取一下。生产环境可以移到函数外,性能更好
if (isDev) {
needLoginPages = getNeedLoginPages()
} else {
needLoginPages = _needLoginPages
}
console.log(needLoginPages.includes(path))
if (needLoginPages.includes(path)) {
const isLogin = isLogined()
if (isLogin) {
return true
}
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
uni.navigateTo({ url: redirectRoute })
return false
}
return true
},
}
export const routeInterceptor = {
install() {
uni.addInterceptor('navigateTo', navigateToInterceptor)
uni.addInterceptor('reLaunch', navigateToInterceptor)
uni.addInterceptor('redirectTo', navigateToInterceptor)
},
}
<template>
<view class="default-layout">
<slot />
<wd-toast />
<wd-message-box />
</view>
</template>
<style lang="scss">
.default-layout {
height: 100vh;
/* #ifdef H5 */
padding-bottom: 50px;
overflow: auto;
/* #endif */
}
</style>
<template>
<view class="text-center p-4">
<slot />
<wd-toast />
<wd-message-box />
</view>
</template>
# 注意事项
> 文件夹名字必须为 `locale`, 这是 `uniapp` 官方约定的,如果改为别的,标题将不能正常切换多语言(其他内容还是正常)。
>
> `xxx.json` 的 `xxx` 多语言标识必须与 `uniapp` 官方约定的一致,否则也会出现 BUG。
>
> 查看截图 `screenshots/i18n.png`。
## 参考文档
[uniapp 国际化开发指南](https://uniapp.dcloud.net.cn/tutorial/i18n.html)
[uniapp 国际化-注意事项](https://uniapp.dcloud.net.cn/api/ui/locale.html#onlocalechange) 最下面的注意事项
{
"weight": "{heavy}KG",
"app.name": "En Title"
}
import { createI18n } from 'vue-i18n'
import en from './en.json'
import zhHans from './zh-Hans.json' // 简体中文
const messages = {
en,
'zh-Hans': zhHans, // key 不能乱写,查看截图 screenshots/i18n.png
}
const i18n = createI18n({
locale: uni.getLocale(), // 获取已设置的语言,fallback 语言需要再 manifest.config.ts 中设置
messages,
})
console.log(uni.getLocale())
console.log(i18n.global.locale)
/**
* 非 vue 文件使用这个方法
* @param { string } localeKey 多语言的key,eg: "app.name"
*/
export const translate = (localeKey: string) => {
if (!localeKey) {
console.error(`[i18n] Function translate(), localeKey param is required`)
return ''
}
const locale = uni.getLocale()
console.log('locale:', locale)
const message = messages[locale]
if (Object.keys(message).includes(localeKey)) {
return message[localeKey]
}
return localeKey
}
export default i18n
{
"app.name": "中文标题",
"weight": "{heavy}公斤"
}
import { createSSRApp } from 'vue'
import uvUI from '@climblee/uv-ui'
import App from './App.vue'
import store from './store'
import { routeInterceptor, requestInterceptor } from './interceptors'
import i18n from './locale/index'
import 'virtual:svg-icons-register'
import 'virtual:uno.css'
import '@/style/index.scss'
// production mock server
// 线上报错,TODO: fix me
// if (import.meta.env.PROD) {
// import('../mock/_mockProdServer').then(({ setupProdMockServer }) => {
// console.log('mockProdServer...')
// setupProdMockServer()
// })
// }
export function createApp() {
const app = createSSRApp(App)
app.use(store)
app.use(i18n)
app.use(uvUI)
app.use(routeInterceptor)
app.use(requestInterceptor)
return {
app,
}
}
{
"name": "unibest",
"appid": "H5871D791",
"description": "",
"versionName": "1.0.0",
"versionCode": "100",
"transformPx": false,
"app-plus": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"compilerVersion": 3,
"splashscreen": {
"alwaysShowBeforeRender": true,
"waiting": true,
"autoclose": true,
"delay": 0
},
"modules": {},
"distribute": {
"android": {
"permissions": [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
],
"minSdkVersion": 30,
"targetSdkVersion": 30,
"abiFilters": [
"armeabi-v7a",
"arm64-v8a"
]
},
"ios": {},
"sdkConfigs": {},
"icons": {
"android": {},
"ios": {}
}
}
},
"quickapp": {},
"mp-weixin": {
"appid": "wxa2abb91f64032a2b",
"setting": {
"urlCheck": false
},
"usingComponents": true
},
"mp-alipay": {
"usingComponents": true
},
"mp-baidu": {
"usingComponents": true
},
"mp-toutiao": {
"usingComponents": true
},
"uniStatistics": {
"enable": false
},
"vueVersion": "3",
"locale": "zh-Hans",
"h5": {
"router": {
"base": "/hello-unibest/"
}
}
}
\ No newline at end of file \ No newline at end of file
# 分包配置
在 `vite.config.ts` 中进行配置。
```ts
import { defineConfig } from 'vite'
import UniPages from '@uni-helper/vite-plugin-uni-pages'
export default defineConfig({
plugins: [
UniPages({
// ... 其他配置
subPackages: [
'src/pages-sub', // 是个数组,可以配置多个
],
}),
],
})
```
<route lang="json5" type="page">
{
style: { navigationBarTitleText: '分包页面 标题' },
}
</route>
<template>
<view class="text-center">
<view class="m-8">http://localhost:9000/#/pages-sub/demo/index</view>
<view class="text-green-500">分包页面demo</view>
</view>
</template>
<script lang="ts" setup>
// code here
</script>
<style lang="scss" scoped>
//
</style>
{
"globalStyle": {
"navigationStyle": "default",
"navigationBarTitleText": "unibest",
"navigationBarBackgroundColor": "#f8f8f8",
"navigationBarTextStyle": "black",
"backgroundColor": "#FFFFFF",
"h5": {}
},
"easycom": {
"autoscan": true,
"custom": {
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue",
"^uv-(.*)": "@climblee/uv-ui/components/uv-$1/uv-$1.vue",
"^wd-(.*)": "wot-design-uni/components/wd-$1/wd-$1.vue",
"^(?!z-paging-refresh|z-paging-load-more)z-paging(.*)": "z-paging/components/z-paging$1/z-paging$1.vue"
}
},
"tabBar": {
"color": "#999999",
"selectedColor": "#018d71",
"backgroundColor": "#F8F8F8",
"borderStyle": "black",
"height": "50px",
"fontSize": "10px",
"iconWidth": "24px",
"spacing": "3px",
"list": [
{
"iconPath": "static/tabbar/home.png",
"selectedIconPath": "static/tabbar/homeHL.png",
"pagePath": "pages/index/index",
"text": "首页"
},
{
"iconPath": "static/tabbar/example.png",
"selectedIconPath": "static/tabbar/exampleHL.png",
"pagePath": "pages/demo/index",
"text": "示例"
}
]
},
"__esModule": true,
"pages": [
{
"path": "pages/index/index",
"type": "home",
"style": {
"navigationStyle": "custom",
"navigationBarTitleText": "首页"
}
},
{
"path": "pages/demo/index",
"type": "page",
"style": {
"navigationBarTitleText": "unibest 示例"
}
},
{
"path": "pages/index/request",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "请求"
}
},
{
"path": "pages/login/index",
"type": "page",
"style": {
"navigationBarTitleText": "登录"
}
},
{
"path": "pages/my/index",
"type": "page",
"style": {
"navigationBarTitleText": "我的"
}
},
{
"path": "pages/demo/base/auto-import",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "auto import component"
}
},
{
"path": "pages/demo/base/css",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "css 格式化问题"
}
},
{
"path": "pages/demo/base/enum",
"type": "page",
"hide": true,
"style": {
"navigationBarTitleText": "enum 使用"
}
},
{
"path": "pages/demo/base/env",
"type": "page",
"style": {
"navigationBarTitleText": "环境获取"
}
},
{
"path": "pages/demo/base/iconfont",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "iconfont"
}
},
{
"path": "pages/demo/base/mock",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "mock"
}
},
{
"path": "pages/demo/base/mp-weixin-share",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "微信分享"
}
},
{
"path": "pages/demo/base/navbar",
"type": "page",
"style": {
"navigationBarTitleText": "自定义导航栏",
"navigationStyle": "custom"
}
},
{
"path": "pages/demo/base/no-navbar",
"type": "page",
"style": {
"navigationBarTitleText": "无导航栏",
"navigationStyle": "custom"
}
},
{
"path": "pages/demo/base/pinia",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "pinia+持久化"
}
},
{
"path": "pages/demo/base/request",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "请求"
}
},
{
"path": "pages/demo/base/request2",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "请求(状态一体化)"
}
},
{
"path": "pages/demo/base/route-interceptor",
"type": "page",
"needLogin": true,
"style": {
"navigationBarTitleText": "路由拦截"
}
},
{
"path": "pages/demo/base/svg",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "svg使用"
}
},
{
"path": "pages/demo/base/throughout",
"type": "page",
"style": {
"navigationBarTitleText": "通屏+下拉刷新+自定义导航栏",
"enablePullDownRefresh": false,
"backgroundColor": "#23c09c",
"app-plus": {
"titleNView": {
"type": "transparent"
}
},
"mp-weixin": {
"navigationStyle": "custom"
}
}
},
{
"path": "pages/demo/base/uni-ui-icons",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "UniUI Icons 使用"
}
},
{
"path": "pages/demo/base/uni-ui",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "UniUI 使用"
}
},
{
"path": "pages/demo/base/unocss-icons",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "UnoCss Icons 使用"
}
},
{
"path": "pages/demo/base/unocss",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "UnoCss 使用"
}
},
{
"path": "pages/demo/base/upload",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "上传"
}
},
{
"path": "pages/demo/base/upload2",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "上传+请求状态"
}
},
{
"path": "pages/demo/base/uv-ui",
"type": "page",
"style": {
"navigationBarTitleText": "uv ui"
}
},
{
"path": "pages/demo/base/vconsole",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "小程序vConsole"
}
},
{
"path": "pages/demo/base/wot",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "wot"
}
},
{
"path": "pages/demo/page/clock",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "动态时钟"
}
},
{
"path": "pages/demo/page/clock2",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "动态时钟-抗锯齿"
}
},
{
"path": "pages/demo/page/floating-bubble",
"type": "page",
"layout": "default",
"hide": true,
"style": {
"navigationBarTitleText": "页面悬浮球"
}
},
{
"path": "pages/demo/page/i18n",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "%app.name%"
}
},
{
"path": "pages/demo/page/sign",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "签字板"
}
},
{
"path": "pages/demo/page/waterfall",
"type": "page",
"style": {
"navigationBarTitleText": "waterfall"
}
},
{
"path": "pages/demo/route-interceptor/index",
"type": "page",
"style": {
"navigationBarTitleText": "登陆拦截"
}
},
{
"path": "pages/demo/route-interceptor/login-auto",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "自动登录(无需拦截)"
}
},
{
"path": "pages/demo/route-interceptor/login-model",
"type": "page",
"style": {
"navigationBarTitleText": "登陆拦截 - 登陆弹窗"
}
},
{
"path": "pages/demo/route-interceptor/login-page",
"type": "page",
"needLogin": true,
"style": {
"navigationBarTitleText": "登陆拦截 - 登陆页面"
}
},
{
"path": "pages/demo/page/echarts/index",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "echarts图表"
}
},
{
"path": "pages/demo/page/img-min/index",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "图片压缩"
}
},
{
"path": "pages/demo/page/lottery/big-wheel",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "大转盘抽奖"
}
},
{
"path": "pages/demo/page/lottery/nine-grid",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "九宫格抽奖"
}
},
{
"path": "pages/demo/page/sp-editor/index",
"type": "page",
"layout": "demo",
"style": {
"navigationBarTitleText": "富文本"
}
},
{
"path": "pages/demo/page/ucharts/index",
"type": "page",
"style": {
"navigationBarTitleText": "ucharts 图表"
}
},
{
"path": "pages/demo/page/z-paging/index",
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "z-paging"
}
}
],
"subPackages": [
{
"root": "pages-sub",
"pages": [
{
"path": "demo/index",
"type": "page",
"style": {
"navigationBarTitleText": "分包页面 标题"
}
}
]
}
]
}
\ No newline at end of file \ No newline at end of file
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: 'auto import component' },
}
</route>
<template>
<div>
<h1>欢迎使用 unibest</h1>
<view class="h-10"></view>
<AppTest>这个组件会自动导入</AppTest>
<view class="h-10"></view>
<AppTest2>这个组件会自动导入</AppTest2>
<view class="text-red-700 mt-4">
不可滥用自动导入,不是全局要用的组件不建议放到 `src/components` 里面,会增加包的体积
</view>
</div>
</template>
<route lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: '请求',
},
}
</route>
<template>
<view class="p-6 text-center">
<view class="my-2">使用的是 laf 云后台</view>
<view class="text-green-400">我的推荐码,可以获得佣金</view>
<!-- #ifdef H5 -->
<view class="my-2">
<a class="my-2" :href="recommendUrl" target="_blank">{{ recommendUrl }}</a>
</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<view class="my-2 text-left text-sm">{{ recommendUrl }}</view>
<!-- #endif -->
<!-- http://localhost:9000/#/pages/index/request -->
<wd-button @click="run" class="my-6">发送请求</wd-button>
<view class="h-12">
<view v-if="loading">loading...</view>
<block v-else>
<view class="text-xl">请求数据如下</view>
<view class="text-green leading-8">{{ JSON.stringify(data) }}</view>
</block>
</view>
<wd-button type="error" @click="reset" class="my-6" :disabled="!data">重置数据</wd-button>
</view>
</template>
<script lang="ts" setup>
import { getFooAPI, postFooAPI, IFooItem } from '@/service/foo'
const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
// const initialData = {
// name: 'initialData',
// id: '1234',
// }
const initialData = undefined
// 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
const { loading, error, data, run } = useRequest<IFooItem>(() => getFooAPI('菲鸽'), {
initialData,
})
const reset = () => {
data.value = initialData
}
</script>
<route lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: '请求',
},
}
</route>
<template>
<view class="p-6 text-center">
<!-- http://localhost:9000/#/pages/index/request -->
<wd-button @click="getFoo" class="my-6">发送请求</wd-button>
<view class="h-12">
<view v-if="loading1">loading...</view>
<block v-else>
<view class="text-xl">请求数据如下</view>
<view class="text-green leading-8">{{ JSON.stringify(data1) }}</view>
</block>
</view>
<wd-button @click="getBar" class="my-6">发送请求2</wd-button>
<view class="h-12">
<view v-if="loading2">loading...</view>
<block v-else>
<view class="text-xl">请求数据如下</view>
<view class="text-green leading-8">{{ JSON.stringify(data2) }}</view>
</block>
</view>
<wd-button type="error" @click="reset" class="my-6" :disabled="!data1 || !data2">
重置数据
</wd-button>
<wd-button type="success" @click="getAllData" class="my-6 ml-2" :disabled="!!data1 || !!data2">
同时发送请求
</wd-button>
</view>
</template>
<script lang="ts" setup>
import { getFooAPI, postFooAPI, IFooItem } from '@/service/foo'
// 适合少部分全局性的接口————多个页面都需要的请求接口,额外编写一个 Service 层
const {
loading: loading1,
error: err1,
data: data1,
run: getFoo,
} = useRequest<IFooItem>(() => getFooAPI('菲鸽'))
const {
loading: loading2,
error: err2,
data: data2,
run: getBar,
} = useRequest<IFooItem>(() => postFooAPI('菲鸽222'))
const reset = () => {
data1.value = undefined
data2.value = undefined
}
const getAllData = () => {
getFoo()
getBar()
}
</script>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: '上传-状态一体化',
},
}
</route>
<template>
<view class="p-4 text-center">
<wd-button @click="run">选择图片并上传</wd-button>
<view v-if="loading" class="text-blue h-10">上传...</view>
<template v-else>
<view class="m-2">上传后返回的接口数据:</view>
<view class="m-2">{{ data }}</view>
<view class="h-80 w-full">
<image v-if="data" :src="data || data" mode="scaleToFill" />
</view>
</template>
</view>
</template>
<script lang="ts" setup>
const { loading, data, run } = useUpload({ user: '菲鸽' })
</script>
<style lang="scss" scoped>
//
</style>
// .test{
// background: #FFF;
// .test1{
// color: #F9FF99;
// }
// }
// 上面的代码在 scss里面格式化是OK的,在Vue里面会有问题
.test {
background: #fff;
.test1 {
color: #f9ff99;
}
}
<route lang="json5" type="page">
{
layout: 'demo',
style: {
navigationBarTitleText: 'css 格式化问题',
},
}
</route>
<template>
<view class="mt-4">
进过多次测试发现,粘贴的css代码块在如下情况时会出现格式化问题:
<view class="ml-4">粘贴的css代码块中类名上面不包含空行(与大小写无关)</view>
<view class="ml-4 text-green-600">1. 中间有空行的,正常,不用处理;</view>
<view class="ml-4 text-red-600">
2. 中间没有空行的,格式化异常,通过 ctrl+Z,ctrl+S 可以搞定
</view>
<image src="./css.png" mode="scaleToFill" class="css-img mt-2" width="688" height="885" />
</view>
</template>
<script lang="ts" setup>
//
</script>
<style lang="scss" scoped>
// 最初的代码如下(版本1)
/*
.test{
background: #FFF;
.test1{
color: #F9FF99;
}
}
*/
// 中间有空行可以正常格式化(版本2)
/*
.test{
background: #FFF;
.test1{
color: #F9FF99;
}
}
*/
// 上面的版本1格式化会变成下面的,错误格式,可以通过 ctrl + z , ctrl + S 解决
// .test {
// background: #fff;
// t1{fff
// color: #F9FF99;
// }
// }
// 上面的版本2格式化会变成下面的,正常
.test {
background: #fff;
.test1 {
color: #f9ff99;
}
}
// 下面是图片的样式,无关
.css-img {
width: 90vw;
max-width: 688px;
height: calc(885 / 688 * 90vw);
max-height: 885px;
}
</style>
<route lang="json5" type="page">
{
hide: true,
style: { navigationBarTitleText: 'enum 使用' },
}
</route>
<template>
<view class="center mt-8 text-green-600">enum 使用,script setup 里面这样写不会报错</view>
</template>
<script lang="ts" setup>
type T = TestEnum.A
const a = 'a' as T
console.log(a)
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
style: { navigationBarTitleText: '环境获取' },
}
</route>
<template>
<view class="mt-4 ml-4">
当前环境 import.meta.env.DEV:
<text class="text-red-500 ml-4">{{ isDev }}</text>
</view>
<view class="mt-4 ml-4">
当前环境所使用的环境文件
<text class="text-red-500 ml-4">{{ VITE_ENV_FILE }}</text>
</view>
<view class="text-red-500 mt-8 ml-4">环境变量的使用与 --mode 参数配合使用</view>
</template>
<script lang="ts" setup>
const isDev = import.meta.env.DEV
const { VITE_ENV_FILE } = import.meta.env
</script>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: 'iconfont',
},
}
</route>
<template>
<view class="m-4">
<text mr-2>iconfont:</text>
<i class="iconfont icon-package text-primary"></i>
<i class="iconfont icon-chat text-primary"></i>
<i class="iconfont icon-my text-primary"></i>
</view>
</template>
<script lang="ts" setup>
//
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
layout: 'demo',
style: {
navigationBarTitleText: 'mock',
},
}
</route>
<template>
<view class="mt-6">
<button @click="getFoo" class="my-4" type="primary">测试 GET 请求</button>
<view class="text-xl">请求数据如下</view>
<view class="text-green h-10">{{ JSON.stringify(data) }}</view>
<view class="text-xl">完整数据</view>
<view class="text-green h-20">{{ JSON.stringify(originalData) }}</view>
<button class="my-8" type="warn" @click="reset">一键清空数据</button>
</view>
</template>
<script lang="ts" setup>
import { getMockAPI } from '@/service/mock'
onLoad(() => {
getFoo()
})
const originalData = ref<IResData<any>>()
const data = ref()
const getFoo = async () => {
const res = await getMockAPI('菲鸽')
data.value = res.data
originalData.value = res
}
const reset = () => {
data.value = undefined
originalData.value = undefined
}
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '微信分享' },
}
</route>
<template>
<view class="text-green">微信分享页</view>
<view class="text-green-500">请在微信小程序中体验,或者开发者工具</view>
<view>1) 默认是不激活”发送给朋友“和”分享到朋友圈“的,如下图</view>
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/wx-share-before.png"
mode="widthFix"
/>
<view>2) 增加了onShareAppMessage和onShareTimeline后,就可以微信分享了,如下图</view>
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/wx-share-after.png"
mode="widthFix"
/>
</template>
<script lang="ts" setup>
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
/** 激活“分享给好友” */
onShareAppMessage((options: Page.ShareAppMessageOption): Page.CustomShareContent => {
console.log('options:', options)
return {
title: '自定义分享标题',
desc: 'unibest 演示示例',
path: '/pages/index/index?id=xxx',
}
})
/** 激活“分享到朋友圈”, 注意:需要先激活“分享给好友” */
onShareTimeline((): Page.ShareTimelineContent => {
return {
title: '自定义分享标题',
query: 'a=1&b=2',
}
})
</script>
<route lang="json5">
{
style: { navigationBarTitleText: '自定义导航栏', navigationStyle: 'custom' },
}
</route>
<template>
<uni-nav-bar
title="自定义导航栏"
left-icon="left"
@clickLeft="goBack"
class="fixed w-full"
:border="false"
:status-bar="true"
></uni-nav-bar>
<view class="h-11" :style="{ paddingTop: safeAreaInsets?.top + 'px' }"></view>
<view>
<fly-content :line="20" />
</view>
</template>
<script lang="ts" setup>
const goBack = () => {
uni.navigateBack()
}
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
</script>
<route lang="json5">
{
style: { navigationBarTitleText: '无导航栏', navigationStyle: 'custom' },
}
</route>
<template>
<fly-navbar />
<view class="bg-green-300 min-h-20" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
<view class="p-4">自定义导航栏,设置"navigationStyle":"custom"</view>
<view class="p-4">通常页面顶部有一个图片或背景色</view>
<view class="p-4">本实例没有导航栏,但是需要返回</view>
</view>
<fly-content :line="20" />
</template>
<script lang="ts" setup>
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
</script>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: 'pinia+持久化' },
}
</route>
<template>
<view class="flex justify-center items-center text-blue-500 mt-4 mb-4">
<view class="w-20">Count: {{ countStore.count }}</view>
<button class="ml-2 mr-2" @click="countStore.decrement">-1</button>
<button class="ml-2 mr-2" @click="countStore.increment">+1</button>
<button class="ml-2 mr-2" @click="countStore.reset">重置</button>
</view>
<view class="m-8 text-4 leading-8">
<view class="text-center">{{ userStore.userInfo }}</view>
<view class="text-center">请观察小程序的store,可以看到是可以正常设置的</view>
<button @click="setUserInfo">设置UserInfo</button>
<button @click="clearUserInfo" class="mt-4">清除UserInfo</button>
<button @click="resetUserStore" class="mt-4">reset UserStore</button>
</view>
</template>
<script lang="ts" setup>
import { useCountStore, useUserStore } from '@/store'
const countStore = useCountStore()
const userStore = useUserStore()
const setUserInfo = () => {
userStore.setUserInfo({ nickname: '菲鸽', avatar: '', token: 'abcdef' })
}
const clearUserInfo = () => {
userStore.clearUserInfo()
}
const resetUserStore = () => {
userStore.reset()
}
</script>
<route lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: '请求',
},
}
</route>
<template>
<view class="mt-6">
<!-- http://localhost:9100/#/pages/index/request -->
<button @click="getFoo" class="my-4">测试 GET 请求</button>
<view class="text-xl">请求数据如下</view>
<view class="text-green h-10">{{ JSON.stringify(data) }}</view>
<view class="text-xl">完整数据</view>
<view class="text-green h-20">{{ JSON.stringify(originalData) }}</view>
<button @click="postFoo" class="my-4">测试 POST 请求</button>
<view class="text-xl">请求数据如下</view>
<view class="text-green h-10">{{ JSON.stringify(data2) }}</view>
<button class="my-8" type="warn" @click="reset">一键清空数据</button>
<view class="my-2">使用的是 laf 云后台</view>
<view class="text-green-400">我的推荐码,可以获得佣金</view>
<!-- #ifdef H5 -->
<view class="my-2 text-center">
<a class="my-2 text-center" :href="recommendUrl" target="_blank">{{ recommendUrl }}</a>
</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<view class="my-2 text-left text-sm">{{ recommendUrl }}</view>
<!-- #endif -->
</view>
</template>
<script lang="ts" setup>
import { getFooAPI, postFooAPI, IFooItem } from '@/service/foo'
const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
onLoad(() => {
getFoo()
postFoo()
})
const originalData = ref<IResData<IFooItem>>()
const data = ref<IFooItem>()
const getFoo = async () => {
const res = await getFooAPI('菲鸽')
data.value = res.data
originalData.value = res
}
const data2 = ref<IFooItem>()
const postFoo = async () => {
const res = await postFooAPI('菲鸽2')
data2.value = res.data
}
const reset = () => {
data.value = undefined
data2.value = undefined
originalData.value = undefined
}
</script>
<route lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: '请求(状态一体化)',
},
}
</route>
<template>
<view class="mt-6">
<view class="text-2xl my-2 text-red-600">1-普通请求</view>
<RequestComp />
<view class="text-2xl my-2 text-red-600">2-上传图片</view>
<UploadComp />
<view class="text-2xl my-2 text-red-600">3-并发请求</view>
<Request2Comp />
</view>
</template>
<script lang="ts" setup>
import RequestComp from './components/request.vue'
import Request2Comp from './components/request2.vue'
import UploadComp from './components/upload.vue'
</script>
<route lang="json5" type="page">
{
needLogin: true,
style: { navigationBarTitleText: '路由拦截' },
}
</route>
<template>
<view class="mt-8 text-center">
<view class="leading-10">
用户是否已登录:
<text>{{ !!userStore?.userInfo?.token }}</text>
</view>
<view class="text-gray">未登录不能来本页面</view>
<view class="text-gray">已登录才能来本页面</view>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store'
const userStore = useUserStore()
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: 'svg使用',
},
}
</route>
<template>
<view class="p-4">
<view class="text-center m-4">svg 多种使用方法</view>
<image src="/static/svg/task.svg" mode="scaleToFill" class="h-20 w-20" />
<image :src="iconUrl" mode="scaleToFill" class="h-20 w-20" />
<image :src="iconUrl2" mode="scaleToFill" class="h-20 w-20" />
<!-- {{ iconRaw }} -->
<view class="text-center m-4 text-blue-500">目前发现,小程序和APP只支持 image 方式</view>
<view class="text-center m-4 text-blue-500">下面的几种方式,都不支持</view>
<!-- #ifdef H5 -->
<TaskComponent class="h-20 w-20" />
<SvgIcon name="task" class="h-20 w-20"></SvgIcon>
<SvgIcon name="dir-task2" class="h-20 w-20"></SvgIcon>
<!-- #endif -->
</view>
</template>
<script lang="ts" setup>
// eslint-disable-next-line import/no-duplicates
import iconUrl from './task.svg'
// eslint-disable-next-line import/no-duplicates
import iconUrl2 from './task.svg?url'
// eslint-disable-next-line import/no-duplicates
import iconRaw from './task.svg?raw'
// #ifdef H5
// 小程序不支持 component 方式引入,运行会报错,APP不报错,但是不生效
// eslint-disable-next-line import/no-duplicates
import TaskComponent from './task.svg?component'
// #endif
</script>
<style lang="scss" scoped>
//
</style>
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1712309809495" class="icon" viewBox="0 0 1049 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4978" xmlns:xlink="http://www.w3.org/1999/xlink" width="65.5625" height="64"><path d="M161.4336 0h624.1024c107.6224 0 161.4336 53.6832 161.4336 161.0752v687.7696c0 107.392-53.8112 161.0752-161.4336 161.0752H161.4336C53.8112 1009.92 0 956.2368 0 848.8448V161.0752C0 53.6832 53.8112 0 161.4336 0z" fill="#01B26A" p-id="4979"></path><path d="M672.1792 352.1024H181.632c-26.88 0-48.64-21.7088-48.64-48.512 0-26.8288 21.76-48.5376 48.64-48.5376h490.5472c26.88 0 48.64 21.7088 48.64 48.5376 0 26.8032-21.76 48.512-48.64 48.512zM485.888 627.84H181.8624c-26.88 0-48.64-21.7344-48.64-48.5376s21.76-48.5376 48.64-48.5376H485.888c26.88 0 48.64 21.76 48.64 48.5376 0 26.8032-21.76 48.5376-48.64 48.5376z" fill="#FFFFFF" p-id="4980"></path><path d="M523.264 761.4208C523.264 906.4448 641.1264 1024 786.432 1024 931.7888 1024 1049.6 906.4448 1049.6 761.4208c0-144.9984-117.8112-262.5536-263.168-262.5536-145.3312 0-263.168 117.5552-263.168 262.5536z" fill="#28D493" fill-opacity=".517" p-id="4981"></path><path d="M786.432 498.944c-128.768-0.1792-238.72 92.6976-259.84 219.4432a262.4512 262.4512 0 0 0 174.72 291.5328h84.0448c89.088 0.1024 161.4336-71.8592 161.6128-160.768V553.5232a261.8368 261.8368 0 0 0-160.512-54.6048z" fill="#00AA69" p-id="4982"></path><path d="M724.0448 918.272a48.64 48.64 0 0 1-44.0832-28.1088 48.4352 48.4352 0 0 1 6.9376-51.7376l71.1936-84.0192v-115.8144c0-26.8032 21.7856-48.5376 48.64-48.5376 26.88 0 48.64 21.7344 48.64 48.5376v133.4528c0 11.4688-4.0704 22.5536-11.4688 31.3088l-82.688 97.6128c-9.216 10.9312-22.8352 17.28-37.1712 17.28z" fill="#FFFFFF" p-id="4983"></path></svg>
\ No newline at end of file \ No newline at end of file
<route lang="json5">
{
style: {
navigationBarTitleText: '通屏+下拉刷新+自定义导航栏',
enablePullDownRefresh: false,
backgroundColor: '#23c09c', // 这个背景色要与页面的.top-section的背景图差不多,这样下拉刷新看起来才比较协调
'app-plus': {
titleNView: {
type: 'transparent',
},
},
'mp-weixin': {
navigationStyle: 'custom',
},
},
}
</route>
<template>
<!-- #ifdef MP-WEIXIN -->
<view class="fly-navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
<!-- 1/3,多于1个页面,用返回图标 -->
<navigator v-if="pages.length > 1" open-type="navigateBack" class="left-icon">
<view class="i-carbon-chevron-left text-current"></view>
</navigator>
<!-- 2/3,只有1个页面,如果不是tabbar,需要首页图标 -->
<!-- 这种情况一般出现在用户直接打开分享出去的详情页面,或者使用redirectTo等API -->
<navigator
v-else-if="!isTabbar"
open-type="switchTab"
url="/pages/index/index"
class="left-icon"
>
<view class="i-carbon-home text-current"></view>
</navigator>
<!-- 3/3,如果当前页就是tabbar页,不用去首页,也就是什么图标都不需要 -->
<view class="title">{{ '我是标题' }}</view>
</view>
<!-- #endif -->
<scroll-view
enable-back-to-top
scroll-y
class="scroll-view-bg flex-1 h-full"
id="scroller"
refresher-enabled
@scrolltolower="onScrollToLower"
@refresherrefresh="onRefresherRefresh"
:refresher-triggered="isTriggered"
>
<view class="top-section" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
<view class="pt-1">顶部区域</view>
<view>可以是标题,也可以是个人中心头像等</view>
<view>建议本区域高度不低于200rpx</view>
</view>
<view class="p-2 leading-6 bg-white">
注意,上面的导航栏渐变效果仅微信端支持,且上面的导航栏无法抽为组件引入使用,否则滚动效果没有了。如果不只是微信小程序使用,可以
onPageScroll 实现全端效果一样,另外如果是app端,还可以配置 titleNView。参考
https://uniapp.dcloud.net.cn/tutorial/page.html#onpagescroll 。
</view>
<view class="bg-white">
<fly-content :line="30" />
</view>
</scroll-view>
</template>
<script lang="ts" setup>
import { onPullDownRefresh } from '@dcloudio/uni-app'
import useNavbarWeixin from '@/hooks/useNavbarWeixin'
const { pages, isTabbar, onScrollToLower, safeAreaInsets } = useNavbarWeixin()
// 发现原生下拉刷新效果并不好,在微信里面只有顶部导航栏下拉才生效,页面区域下拉不生效,体验不好,结合自定义下拉刷新效果很好
onPullDownRefresh(() => {
setTimeout(function fn() {
console.log('refresh - onPullDownRefresh')
// 关闭动画
uni.stopPullDownRefresh()
}, 1000)
})
// 当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherRefresh = async () => {
// 开始动画
isTriggered.value = true
setTimeout(function fn() {
console.log('refresh - onRefresherRefresh')
// 关闭动画
isTriggered.value = false
}, 1000)
}
</script>
<style lang="scss">
.scroll-view-bg {
// 这个背景色要与.top-section的背景图差不多,这样下拉刷新看起来才比较协调
background-color: #23c09c;
}
// 这个区域最好要大于200rpx,效果会更好
.top-section {
display: flex;
flex-direction: column;
align-items: center;
min-height: 200rpx;
padding: 40rpx 0;
line-height: 2;
color: #fff;
background-image: url('https://oss.laf.run/ukw0y1-site/hello-unibest-images/top-bg.png');
background-size: cover;
}
.fly-navbar {
position: fixed;
top: 0;
left: 0;
z-index: 9;
width: 750rpx;
color: #000;
background-color: transparent;
.left-icon {
position: absolute;
left: 0;
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
font-size: 44rpx;
color: #000;
}
.title {
display: flex;
align-items: center;
justify-content: center;
height: 44px;
font-size: 32rpx;
color: transparent;
}
}
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: 'UniUI Icons 使用' },
}
</route>
<template>
<view class="m-4">
<uni-icons type="contact" size="30"></uni-icons>
<uni-icons type="contact" size="30" color="red"></uni-icons>
<uni-icons type="contact" size="30" class="text-green"></uni-icons>
<uni-icons type="contact" size="30" color="red" class="text-green"></uni-icons>
<uni-icons type="contact" size="30" color="red" class="text-green"></uni-icons>
<uni-icons type="contact" color="red" class="text-green w-4"></uni-icons>
<uni-icons type="contact" color="red" class="text-green w-8"></uni-icons>
<uni-icons :type="iconName" :color="colorName" class="text-green w-8"></uni-icons>
</view>
</template>
<script lang="ts" setup>
const iconName = ref<string>('contact')
const colorName = ref<string>('red')
onLoad(() => {
setTimeout(() => {
iconName.value = 'chat'
colorName.value = 'green'
}, 1000)
})
</script>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: 'UniUI 使用' },
}
</route>
<template>
<uni-card>
<text>这是一个基础卡片示例,内容较少,此示例展示了一个没有任何属性不带阴影的卡片。</text>
</uni-card>
<uni-badge text="99"></uni-badge>
<uni-rate :value="3" />
<view>
<button @click="open">打开弹窗</button>
<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
底部弹出 Popup 自定义圆角
</uni-popup>
</view>
</template>
<script lang="ts" setup>
const popup = ref()
const open = () => {
popup.value?.open()
}
</script>
{
"icon2": "i-carbon-3d-cursor-alt",
"nest2": {
"nest2": {
"icon": "i-carbon-add-alt"
}
}
}
export const icon = 'i-carbon-3d-cursor'
export const nest = {
nest: {
icon: 'i-carbon-3d-ica',
},
}
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: 'UnoCss Icons 使用' },
}
</route>
<template>
<view class="m-4">
<view class="mb-2">
这里只装了carbon的图表库,网址:
<a href="https://icones.js.org/collection/carbon" target="_blank">
https://icones.js.org/collection/carbon
</a>
(非H5环境,请使用浏览器打开)
</view>
<view class="i-carbon-car" />
<view class="i-carbon-car text-red" />
<button class="i-carbon-sun dark:i-carbon-moon" />
<view class="h-10"></view>
<view class="i-carbon-user-avatar text-red" />
<view :class="`i-carbon-user-avatar`" />
<view class="ml-2"></view>
<view :class="iconName" />
<view :class="iconName2" />
<view :class="iconName3" />
<view class="my-4 text-red">经过测试,动态图片从别的文件导入无法生效</view>
<wd-tabbar-item title="首页" icon="home"></wd-tabbar-item>
<wd-tabbar-item :value="2" icon="cart" title="分类">
<template #icon>
<view :class="iconName2" />
</template>
</wd-tabbar-item>
<wd-tabbar-item :value="2" icon="cart" title="分类">
<template #icon>
<view :class="iconName3" />
</template>
</wd-tabbar-item>
</view>
</template>
<script lang="ts" setup>
import { icon, nest } from './unocss-icon'
import { icon2, nest2 } from './unocss-icon.json'
// 只需要把外面的在这里写一遍就能生效了!注释掉也是生效的,但是必须要有
// 'i-carbon-3d-cursor-alt'
const iconName = ref<string>('i-carbon-car')
const iconName2 = ref<string>('i-carbon-car')
const iconName3 = ref<string>('i-carbon-car')
onLoad(() => {
setTimeout(() => {
iconName.value = 'i-carbon-4k'
iconName2.value = icon
iconName3.value = icon2
}, 1000)
setTimeout(() => {
console.log(nest.nest.icon, nest2.nest2.icon)
iconName2.value = nest.nest.icon
iconName3.value = nest2.nest2.icon
}, 2000)
})
</script>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: 'UnoCss 使用' },
}
</route>
<template>
<view class="flex flex-col justify-center items-center text-5 h-12 leading-12 mt-20">
<view class="text-green-500">文字颜色 text-light-50</view>
<view class="text-red-500">文字颜色 text-red-500</view>
<view class="bg-green-500 mt-4">背景色 bg-light-50</view>
<view class="bg-red-500 mt-4">背景色 bg-red-500</view>
</view>
</template>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: '上传',
},
}
</route>
<template>
<view class="p-4 text-center">
<wd-button @click="chooseImage">选择图片并上传</wd-button>
<view class="m-2">上传后返回的图片地址:</view>
<view class="m-2">{{ imgStr }}</view>
<view class="h-80 w-full">
<image v-if="imgStr" :src="imgStr" mode="scaleToFill" />
</view>
</view>
</template>
<script lang="ts" setup>
const imgStr = ref('')
const chooseImage = () => {
// #ifdef MP-WEIXIN
// 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
// 微信小程序在2023年10月17日之后,使用本API需要配置隐私协议
uni.chooseMedia({
count: 1,
mediaType: ['image'],
success: (res) => {
console.log(res)
const tempFilePath = res.tempFiles[0].tempFilePath
uni.uploadFile({
url: 'https://ukw0y1.laf.run/upload',
filePath: tempFilePath,
name: 'file',
formData: {
user: '菲鸽',
},
success: (uploadFileRes) => {
console.log(typeof uploadFileRes.data)
const data = JSON.parse(uploadFileRes.data)
imgStr.value = data.data.url
},
})
},
})
// #endif
// #ifndef MP-WEIXIN
uni.chooseImage({
count: 1,
success: (res) => {
console.log(res)
const tempFilePath = res.tempFilePaths[0]
uni.uploadFile({
url: 'https://ukw0y1.laf.run/upload',
filePath: tempFilePath,
name: 'file',
formData: {
user: '菲鸽',
},
success: (uploadFileRes) => {
console.log(typeof uploadFileRes.data)
const data = JSON.parse(uploadFileRes.data)
imgStr.value = data.data.url
},
})
},
})
// #endif
}
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: '上传+请求状态',
},
}
</route>
<template>
<view class="p-4 text-center">
<wd-button @click="run">选择图片并上传</wd-button>
<view v-if="loading" class="text-blue h-10">上传...</view>
<template v-else>
<view class="m-2">上传后返回的图片地址:</view>
<view class="m-2">{{ data }}</view>
<view class="h-80 w-full">
<image v-if="data" :src="data" mode="scaleToFill" />
</view>
</template>
</view>
</template>
<script lang="ts" setup>
const { loading, data, run } = useUpload<string>({ user: '菲鸽' })
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
style: { navigationBarTitleText: 'uv ui' },
}
</route>
<template>
<view class="mt-10">
<uv-button type="primary" @click="remakeQc">重新生成二维码</uv-button>
<view class="center mt-8">
<uv-qrcode
ref="qrcode"
size="200px"
value="https://h5.uvui.cn"
:options="options"
></uv-qrcode>
</view>
<view class="m-4 flex">
<uv-icon name="home"></uv-icon>
<uv-icon name="home" color="red"></uv-icon>
<uv-icon name="home" class="text-green"></uv-icon>
<uv-icon name="home" color="red" class="text-green"></uv-icon>
<uv-icon name="home" color="red" class="text-green" size="20"></uv-icon>
<uv-icon name="home" color="red" class="text-green w-10 h-10" size="20"></uv-icon>
<uv-icon name="home" color="red" class="text-green w-20 h-20"></uv-icon>
<uv-icon name="home" color="red" class="text-green w-10" size="20"></uv-icon>
<uv-icon :name="iconName"></uv-icon>
</view>
<view class="m-4">
<view>富文本也是支持的:</view>
<uv-parse :content="content"></uv-parse>
</view>
<uv-popup ref="popup" @change="change">
<view>
<text>
丙辰中秋,欢饮达旦,大醉,作此篇,兼怀子由。 明月几时有?把酒问青天。
不知天上宫阙,今夕是何年。我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间。
转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?人有悲欢离合,月有阴晴圆缺,此事古难全。
但愿人长久,千里共婵娟。
</text>
</view>
</uv-popup>
<button @click="open">打开</button>
</view>
</template>
<script lang="ts" setup>
const content = `<div>
<p style="color:red;" >露从今夜白,月是故乡明</p>
<img src="https://cdn.uviewui.com/uview/swiper/2.jpg" />
</div>
`
console.log(uni.$uv.os())
console.log(uni.$uv.sys())
console.log(uni.$uv.trim(' abc ')) // 去除两端空格
console.log(uni.$uv.random(1, 3)) // 获取随机数
const qrcode = ref(null)
const options = reactive({
size: 300,
useDynamicSize: false,
margin: 10,
backgroundColor: '#fff',
// 指定二维码前景,一般可在中间放logo
foregroundImageSrc: '/static/logo.svg',
})
const remakeQc = () => {
qrcode.value.remake({
success: () => {
console.log('生成成功')
},
fail: (err) => {
console.log(err)
},
})
}
const iconName = ref<string>('level')
onLoad(() => {
setTimeout(() => {
iconName.value = 'chat'
}, 1000)
})
const popup = ref()
const open = () => {
popup.value?.open()
}
const change = (e) => {
console.log('弹窗状态改变:', e)
}
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '小程序vConsole' },
}
</route>
<template>
<view class="text-5 h-8 leading-8">
<view class="text-red-500">在非正式版小程序里面已经集成了VConsole</view>
<view class="text-blue-500 mb-2">开启方式如下面</view>
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/vconsole-1.png"
mode="widthFix"
/>
<view class="text-blue-500 m-2">然后页面上会出现一个 `vConsole` 的调试按钮,如下图</view>
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/vconsole-2.png"
mode="widthFix"
/>
</view>
</template>
<route lang="json5" type="page">
{
layout: 'demo',
style: {
navigationBarTitleText: 'wot',
},
}
</route>
<template>
<view class="center pt-4 flex-col">
<wd-button>主要按钮</wd-button>
<wd-button type="success">成功按钮</wd-button>
<wd-button type="info">信息按钮</wd-button>
<wd-button type="warning">警告按钮</wd-button>
<wd-button type="error">危险按钮</wd-button>
<view class="h-10"></view>
<wd-button @click="handleClick">展示幕帘</wd-button>
<wd-curtain
:value="value"
:width="300"
src="https://via.placeholder.com/400x200.png/3c9cff/fff"
@close="handleClose"
></wd-curtain>
<view class="mt-4">
可以通过 unocss class 类改颜色,也可以通过 color 属性修改颜色,同时存在时以 color 为优先
</view>
<view class="mt-4">
可以通过 unocss class 类改颜色,也可以通过 color 属性修改颜色,同时存在时以 color 为优先
</view>
<view class="flex m-4">
<wd-icon name="add-circle"></wd-icon>
<wd-icon name="add-circle" color="red"></wd-icon>
<wd-icon class="text-green" name="add-circle"></wd-icon>
<wd-icon class="text-green" name="add-circle" color="red"></wd-icon>
<wd-icon class="text-green w-10 h-10" name="add-circle" color="red"></wd-icon>
<wd-icon :name="iconName"></wd-icon>
</view>
<view @click="closeOutside" class="mt-4">
<wd-popover v-model="show" content="popover content" @change="handleChange">
<wd-button>点击展示</wd-button>
</wd-popover>
</view>
<view class="mt-4">
<wd-button @click="showModal">点击显示Modal</wd-button>
<wd-button @click="showToast">点击显示toast</wd-button>
</view>
</view>
</template>
<script lang="ts" setup>
import { useQueue, useMessage, useToast } from 'wot-design-uni'
const { closeOutside } = useQueue()
const message = useMessage()
const toast = useToast()
const show = ref<boolean>(false)
function handleChange({ show }) {
console.log(show)
}
const showModal = () => {
// 顺便测试 message 的使用
message.show('显示隐藏切换')
}
const showToast = () => {
// 顺便测试 message 的使用
toast.success('unibest 你值得拥有')
}
const value = ref<boolean>(false)
function handleClick() {
value.value = true
}
function handleClose() {
value.value = false
}
const iconName = ref<string>('add-circle')
onLoad(() => {
setTimeout(() => {
iconName.value = 'check'
}, 1000)
})
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5">
{
style: { navigationBarTitleText: 'unibest 示例' },
}
</route>
<template>
<view class="bg-slate-100 min-h-full box-border pb-1">
<view class="tab-container sticky top-0 bg-white px-4 center h-12 z-1">
<view
class="w-full text-center h-10 leading-10 rounded-md"
:class="{ 'bg-green-300': idx === currIdx }"
v-for="(tab, idx) in tabList"
:key="tab.id"
>
<view class="font-800" @click="currIdx = idx">{{ tab.title }}</view>
</view>
</view>
<view class="bg-slate-100 px-4 pt-3">
<view class="list-container">
<view v-for="item in currContentList" :key="item.path" class="mb-3">
<view
class="flex bg-white items-center justify-between p-3 mb-2"
@click="goDetailPage(item.path)"
>
<text class="flex-1 text-4 text-dark">{{ item.title }}</text>
<text class="i-carbon-chevron-right"></text>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts" name="TestIndex">
import pagesJson from '@/pages.json'
const handleTitle = (str?: string) => {
if (!str) {
return '标题'
}
if (/%.*%/.test(str)) {
return '多语言'
}
return str
}
/** 基本功能 */
const baseDemos = pagesJson.pages
.filter((e) => e.path.startsWith('pages/demo/base') && !e.hide)
.map((e) => ({
title: handleTitle(e.style?.navigationBarTitleText),
path: e.path,
}))
/** 页面功能 */
const pageDemos = pagesJson.pages
.filter((e) => e.path.startsWith('pages/demo/page') && !e.hide)
.map((e) => ({
title: handleTitle(e.style?.navigationBarTitleText),
path: e.path,
}))
const routeInterceptionList = [
{
title: '说明页面',
path: 'pages/demo/route-interceptor/index',
},
{
title: '单独登录页面',
path: 'pages/demo/route-interceptor/login-page?name=feige&age=30',
},
{
title: '登录弹窗',
path: 'pages/demo/route-interceptor/login-model?name=feige&age=30',
},
{
title: '静默登录',
path: 'pages/demo/route-interceptor/login-auto?name=feige&age=30',
},
]
const tabList = reactive([
{
id: 1,
title: '基础功能',
list: baseDemos,
},
{
id: 2,
title: '登录拦截',
list: routeInterceptionList,
},
{
id: 3,
title: '页面功能',
list: pageDemos,
},
])
const currIdx = ref(0)
const currContentList = computed(() => {
return tabList[currIdx.value].list
})
const goDetailPage = (path: string) => {
const url = `/${path}`
uni.navigateTo({
url,
})
}
</script>
<style>
page {
height: 100%;
}
.tab-container {
display: flex;
}
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '动态时钟' },
}
</route>
<template>
<view class="mt-4 h-10 text-center">动态时钟</view>
<view class="clock-box">
<view class="clock" :style="{ '--ds': ds, '--dm': dm, '--dh': dh }">
<view class="clock-pane">
<text class="clock-num" :style="{ '--i': n }" v-for="n in 12" :key="n">{{ n }}</text>
</view>
<view class="clock-hour"></view>
<view class="clock-min"></view>
<view class="clock-sec"></view>
</view>
</view>
</template>
<script lang="ts" setup>
const d = new Date()
const h = d.getHours()
const m = d.getMinutes()
const s = d.getSeconds()
const ds = ref(s)
const dm = ref(m + s / 60)
const dh = ref(h + m / 60 + s / 3600)
</script>
<style lang="scss">
.clock-box {
display: flex;
align-items: center;
justify-content: center;
}
.clock {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 350px;
height: 350px;
font-size: 24px;
border-radius: 20px;
box-shadow: 2px 2px 20px #0000001a;
--step: 60s;
}
.clock::before {
position: absolute;
width: 300px;
height: 300px;
content: '';
background: repeating-conic-gradient(from -0.5deg, #333 0 1deg, transparent 0deg 30deg),
repeating-conic-gradient(from -0.5deg, #ccc 0 1deg, transparent 0deg 6deg);
border-radius: 50%;
mask: radial-gradient(transparent 145px, red 0);
}
.clock-pane {
position: absolute;
width: 250px;
height: 250px;
transform: translateX(-125px);
}
.clock-num {
position: absolute;
offset-path: path(
'M250 125c0 69.036-55.964 125-125 125S0 194.036 0 125 55.964 0 125 0s125 55.964 125 125z'
);
offset-distance: calc(var(--i) * 10% / 1.2 - 25%);
offset-rotate: 0deg;
}
.clock-hour {
position: absolute;
width: 4px;
height: 60px;
background: #333;
transform: translateY(-50%) rotate(0);
transform-origin: center bottom;
animation: clock calc(var(--step) * 60 * 12) infinite linear;
animation-delay: calc(-1 * var(--step) * var(--dh) * 60);
}
.clock-min {
position: absolute;
width: 4px;
height: 90px;
background: #333;
transform: translateY(-50%) rotate(0);
transform-origin: center bottom;
animation: clock calc(var(--step) * 60) infinite linear;
animation-delay: calc(-1 * var(--step) * var(--dm));
}
.clock-sec {
position: absolute;
width: 2px;
height: 120px;
background: red;
transform: translateY(-50%) rotate(0);
transform-origin: center bottom;
animation: clock var(--step) infinite steps(60);
animation-delay: calc(-1 * var(--step) * var(--ds) / 60);
}
.clock-sec::after {
position: absolute;
bottom: 0;
left: 50%;
width: 10px;
height: 10px;
content: '';
background: #fff;
border: 4px solid #333;
border-radius: 50%;
transform: translate(-50%, 50%);
}
@keyframes clock {
to {
transform: translateY(-50%) rotate(360deg);
}
}
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '动态时钟-抗锯齿' },
}
</route>
<template>
<view class="mt-4 h-10 text-center">动态时钟</view>
<view class="clock-box">
<view class="clock" :style="{ '--ds': ds, '--dm': dm, '--dh': dh }">
<view class="clock-pane">
<text class="clock-num" :style="{ '--i': n }" v-for="n in 12" :key="n">{{ n }}</text>
</view>
<view class="clock-scales">
<text class="clock-scale" :style="{ '--i': n }" v-for="n in 60" :key="n"></text>
</view>
<view class="clock-hour"></view>
<view class="clock-min"></view>
<view class="clock-sec"></view>
</view>
</view>
</template>
<script lang="ts" setup>
const d = new Date()
const h = d.getHours()
const m = d.getMinutes()
const s = d.getSeconds()
const ds = ref(s)
const dm = ref(m + s / 60)
const dh = ref(h + m / 60 + s / 3600)
</script>
<style lang="scss">
.clock-box {
display: flex;
align-items: center;
justify-content: center;
}
.clock {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 350px;
height: 350px;
font-size: 24px;
border-radius: 20px;
box-shadow: 2px 2px 20px #0000001a;
--step: 60s;
}
.clock-pane {
position: absolute;
width: 250px;
height: 250px;
transform: translateX(-125px);
}
.clock-scales {
position: absolute;
width: 250px;
height: 250px;
transform: translate(125px, -25px);
}
.clock-scale {
position: absolute;
top: 0;
left: 0;
width: 2px;
height: 4px;
background: #ccc;
transform-origin: 0 150px;
&:nth-child(5n + 1) {
width: 4px;
height: 6px;
background: #333;
}
}
@for $i from 1 through 60 {
.clock-scale:nth-child(#{$i}) {
transform: rotate(#{($i - 1) * 6deg});
}
}
.clock-num {
position: absolute;
offset-path: path(
'M250 125c0 69.036-55.964 125-125 125S0 194.036 0 125 55.964 0 125 0s125 55.964 125 125z'
);
offset-distance: calc(var(--i) * 10% / 1.2 - 25%);
offset-rotate: 0deg;
}
.clock-hour {
position: absolute;
width: 4px;
height: 60px;
background: #333;
transform: translateY(-50%) rotate(0);
transform-origin: center bottom;
animation: clock calc(var(--step) * 60 * 12) infinite linear;
animation-delay: calc(-1 * var(--step) * var(--dh) * 60);
}
.clock-min {
position: absolute;
width: 4px;
height: 90px;
background: #333;
transform: translateY(-50%) rotate(0);
transform-origin: center bottom;
animation: clock calc(var(--step) * 60) infinite linear;
animation-delay: calc(-1 * var(--step) * var(--dm));
}
.clock-sec {
position: absolute;
width: 2px;
height: 120px;
background: red;
transform: translateY(-50%) rotate(0);
transform-origin: center bottom;
animation: clock var(--step) infinite steps(60);
animation-delay: calc(-1 * var(--step) * var(--ds) / 60);
}
.clock-sec::after {
position: absolute;
bottom: 0;
left: 50%;
width: 10px;
height: 10px;
content: '';
background: #fff;
border: 4px solid #333;
border-radius: 50%;
transform: translate(-50%, 50%);
}
@keyframes clock {
to {
transform: translateY(-50%) rotate(360deg);
}
}
</style>
import { useEcharts } from '@/hooks/useEcharts'
import { ref } from 'vue'
// 折线图
export const useLineEcharts = (): any => {
// 折线图配置项数据
// 每次编写新类型的图表时,只需要复制一份修改这里的配置即可
// 应用 这个类型的图表时,只需在 .vue 文件中通过 set 修复数据即可,或者简单的样式修改,如果样式过于复杂,可以重新建立一个 linkHookB 等等
const option = ref({
xAxis: {
data: [12, 13, 10, 13, 9, 23, 21, 32, 12, 15, 13, 10],
boundaryGap: false,
axisTick: {
show: false,
},
axisLine: {
show: true,
lineStyle: {
color: '#0C4787',
},
},
axisLabel: {
show: true,
color: '#000000',
},
},
grid: {
left: 5,
right: 16,
bottom: 5,
top: 20,
containLabel: true,
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
},
padding: [5, 10],
},
yAxis: {
axisTick: {
show: false,
},
splitLine: {
show: false,
},
axisLine: {
show: true,
lineStyle: {
color: '#0C4787',
},
},
axisLabel: {
show: true,
color: '#000000',
},
},
series: {
smooth: true,
type: 'line',
data: [12, 13, 10, 13, 9, 23, 21, 32, 12, 15, 13, 10],
animationDuration: 2800,
animationEasing: 'cubicInOut',
symbol: 'circle',
color: '#fed42b',
symbolSize: 8,
lineStyle: {
color: '#fed42b', // 改变折线颜色
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: '#fed42b', // 0% 处的颜色
},
{
offset: 1,
color: 'rgba(254, 212, 43, 0.1)', // 100% 处的颜色
},
],
global: false, // 缺省为 false
},
},
},
})
return useEcharts(option)
}
// 柱状图
export const useBarEcharts = (): any => {
const option = ref({
xAxis: {
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: {
show: false,
},
axisLine: {
show: true,
lineStyle: {
color: '#0C4787',
},
},
axisLabel: {
show: true,
color: '#000000',
},
},
grid: {
left: 5,
right: 16,
bottom: 5,
top: 20,
containLabel: true,
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
},
padding: [5, 10],
},
yAxis: {
axisTick: {
show: false,
},
splitLine: {
show: false,
},
axisLine: {
show: true,
lineStyle: {
color: '#0C4787',
},
},
axisLabel: {
show: true,
color: '#000000',
},
},
series: {
type: 'bar',
data: [120, 200, 150, 80, 70, 110, 130],
animationDuration: 2800,
animationEasing: 'cubicInOut',
color: '#fed42b',
barWidth: 10,
itemStyle: {
barBorderRadius: [3, 3, 0, 0],
},
},
})
return useEcharts(option)
}
<route type="page" lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: 'echarts图表',
},
}
</route>
<template>
<view>折线图1</view>
<view style="width: 100%; height: 200px">
<l-echart ref="lineChartRef" />
</view>
<view>折线图2</view>
<view style="width: 100%; height: 200px">
<l-echart ref="lineChartRef2" />
</view>
<view>柱状图</view>
<view style="width: 100%; height: 200px">
<l-echart ref="barChartRef" />
</view>
<button @click="changeLineChartData">切换折线图1数据</button>
<button @click="changeBarChartData">改变柱状图样式</button>
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
import { useBarEcharts, useLineEcharts } from './echartsData'
import { set } from 'lodash-es'
const [lineChartRef, lineOption, lineDraw] = useLineEcharts()
const [lineChartRef2, lineOption2, lineDraw2] = useLineEcharts()
const [barChartRef, barOption, barDraw] = useBarEcharts()
// 初始化 折线图表1
const initLineChart = () => {
set(lineOption.value, 'series.data', [120, 132, 101, 134, 90, 230, 210, 220, 182, 191, 234, 290])
lineDraw()
}
// 初始化 折线图表2
const initLineChart2 = () => {
set(
lineOption2.value,
'series.data',
[220, 182, 191, 234, 290, 330, 310, 320, 302, 301, 334, 390],
)
lineDraw2()
}
// 初始化 柱状图表
const initBarChart = () => {
set(barOption.value, 'series.data', [120, 200, 150, 80, 70, 110, 130])
barDraw()
}
// 切换折线图数据
const changeLineChartData = () => {
set(lineOption.value, 'series.data', [324, 332, 301, 334, 390, 330, 320, 302, 301, 334, 390, 330])
lineDraw()
}
// 改变柱状图样式
const changeBarChartData = () => {
set(barOption.value, 'series.color', '#5677fc')
barDraw()
}
onMounted(() => {
initLineChart()
initLineChart2()
initBarChart()
})
</script>
<style>
/* 暗黑模式 start */
.wot-theme-dark {
color: #f5f5f5;
background: #222;
--theme-bg-color: #222;
}
</style>
<route lang="json5">
{
layout: 'default',
hide: true,
style: { navigationBarTitleText: '页面悬浮球' },
}
</route>
<template>
<view>
<movable-area class="movable-area">
<movable-view
:style="`--size:${ballSize}px`"
class="movable-view"
direction="all"
:x="x"
:y="y"
@change="onChange"
@touchend.prevent="onTouchEnd"
>
<view class="w-full h-full rounded-full bg-green-400"></view>
</movable-view>
</movable-area>
<view>页面其他元素</view>
<view>可以正常触发点击事件吗?答案是可以的</view>
<button @click="onClick">按钮</button>
<view>{{ x }}</view>
<view>{{ y }}</view>
<view @click="onSet">点击设置</view>
</view>
</template>
<script lang="ts" setup name="FloatingBubble">
const { windowHeight, windowWidth } = uni.getSystemInfoSync()
const ballSize = 60
const x = ref(windowWidth - ballSize) // 靠右侧
const y = ref(windowHeight - ballSize - 20) // 距离底部20px
const middleX = (windowWidth - ballSize) / 2
const onChange = (e) => {
const { x: _x, y: _y } = e.detail
x.value = _x
y.value = _y
}
// TODO: 期望最终落点不靠左右两边时,会自动回到两边,有一定的动画效果
const onTouchEnd = (e) => {
console.log('onTouchEnd', e)
// TODO:为啥这里设置的不生效了,原生不会移动到设置的地方,onSet里面可以。这里直接执行onSet也不行
// 这里被我解决了
const tid = setTimeout(() => {
if (x.value < middleX) {
x.value = 0
} else {
x.value = windowWidth - ballSize
}
clearTimeout(tid)
}, 0)
}
const onClick = () => {
uni.showToast({
title: 'yes',
icon: 'none',
})
}
const onSet = () => {
x.value = 100
y.value = 100
}
</script>
<style lang="scss">
.movable-area {
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100%;
height: 100%;
pointer-events: none; // 设置area元素不可点击,则事件便会下移至页面下层元素
.movable-view {
width: var(--size);
height: var(--size);
pointer-events: auto; // 必须设置,否则无法点击
}
}
</style>
<route lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: '%app.name%',
},
}
</route>
<template>
<view class="center flex-col mt-6">
<view class="text-red-500 p-4 leading-6">
经过我的测试发现,小程序里面会有2处BUG:
<view>1. 页面标题多语言不生效</view>
<view>2. 多语言传递的参数不生效,如下 heavy</view>
</view>
<view class="text-green-500">多语言测试</view>
<view class="m-4">{{ $t('app.name') }}</view>
<view class="m-4">{{ $t('weight', { heavy: 100 }) }}</view>
<view class="text-green-500 mt-12">切换语言</view>
<view class="uni-list">
<radio-group @change="radioChange" class="radio-group">
<label class="uni-list-cell uni-list-cell-pd" v-for="item in languages" :key="item.value">
<view>
<radio :value="item.value" :checked="item.value === current" />
</view>
<view>{{ item.name }}</view>
</label>
</radio-group>
</view>
<!-- http://localhost:9100/#/pages/index/i18n -->
<button @click="testI18n" class="mt-20 mb-44">测试弹窗</button>
</view>
</template>
<script lang="ts" setup>
import i18n from '@/locale/index'
import { testI18n } from '@/utils/index'
const current = ref(uni.getLocale())
const languages = [
{
value: 'zh-Hans',
name: '中文',
checked: 'true',
},
{
value: 'en',
name: '英文',
},
]
const radioChange = (evt) => {
// console.log(evt)
current.value = evt.detail.value
// 下面2句缺一不可!!!
uni.setLocale(evt.detail.value)
i18n.global.locale = evt.detail.value
}
</script>
<style lang="scss">
.uni-list {
position: relative;
display: flex;
flex-direction: column;
width: 100%;
background-color: #fff;
border-radius: 12px;
}
.radio-group {
width: 200px;
margin: 10px auto;
border-radius: 12px;
}
.uni-list-cell {
position: relative;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 10px;
background-color: #bcecd1;
}
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '图片压缩' },
}
</route>
<script setup lang="ts">
import testBgImg from './test-bg.png'
</script>
<template>
<view class="m-4 text-center">
<view class="mb-2 text-orange-500">
原始图片是一个很大的,2.5M,build之后生成的图片只有1.1M,体积下降 56%
</view>
<view class="mb-4 text-red-500">
微信小程序有包体积的限制,图片通常使用线上地址,不用本地图片就用不上这个插件了。
</view>
<!-- #ifdef MP -->
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/imgmin-bg.png"
mode="scaleToFill"
/>
<!-- #endif -->
<!-- #ifndef MP -->
<image :src="testBgImg" mode="scaleToFill" />
<!-- #endif -->
<view class="mb-4">对比图如下2图,如果看不清请看代码原图</view>
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/imgmin-before.png"
mode="widthFix"
class="w-full"
/>
<image
src="https://oss.laf.run/ukw0y1-site/hello-unibest-images/imgmin-after.png"
mode="widthFix"
class="w-full"
/>
</view>
</template>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '大转盘抽奖' },
}
</route>
<template>
<view class="text-center">
<view class="container">
<view class="prize-list" :style="styleObj">
<view
class="prize-item"
v-for="(item, index) in prizeList"
:key="item.id"
:style="prizeStyle(index)"
>
<image :src="item.pic" class="gift-img" />
<text class="gift-name">{{ item.name }}</text>
</view>
</view>
<view class="lottery-btn" @click="start"></view>
</view>
</view>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue'
// TODO: fix 微信小程序里面会报错
// import targetImg from 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/ui.png'
let isLeaved = false
// onBackPress(({ from }: { from: 'backbutton' | 'navigateBack' }) => {
// console.log('onBackPress', from)
// isLeaved = true
// return false
// })
// onBackPress 有兼容性问题,统一使用 onUnload,测试验证OK
onUnload(() => {
isLeaved = true
console.log('onUnload', isLeaved)
})
// 后台配置的奖品数据
const prizeList = [
{
id: 0,
name: '双肩包',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/backpack.jpeg',
},
{
id: 1,
name: '积木',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/jimu.jpg',
},
{
id: 2,
name: '红包',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/red-envelope.jpg',
},
{
id: 3,
name: '茶具',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/tea-set.jpg',
},
{
id: 4,
name: '可爱脸',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/tushetou.jpg',
},
{
id: 5,
name: '挖掘机',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/wajueji.jpg',
},
{
id: 6,
name: '无辜脸',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/xiaolian.jpg',
},
{
id: 7,
name: '烟灰缸',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/yanhuigang.jpg',
},
]
let isRunning = false // 是否正在抽奖
const baseRunAngle = 360 * 5 // 总共转动角度 至少5圈
let prizeId = 0 // 中奖id
// 平均每个奖品角度
const rotateAngle = computed(() => {
const _degree = 360 / prizeList.length
return _degree
})
// 要执行总角度数
const totalRunAngle = ref(baseRunAngle - (prizeId + 0.5) * rotateAngle.value)
// 计算绘制转盘背景
const bgColor = (() => {
const [c1, c2] = ['#5352b3', '#363589']
// repeating-conic-gradient(red 0 15deg, blue 15deg 30deg);
return `background: repeating-conic-gradient(${c1} 0 ${rotateAngle.value}deg,
${c2} ${rotateAngle.value}deg ${2 * rotateAngle.value}deg);`
})()
const styleObj = ref(bgColor)
// 每个奖品布局
const prizeStyle = computed(() => {
const _degree = rotateAngle.value
return (i) => {
// 外框大小设置为90vw,里面是一半,45vw
return `
width: ${2 * 45 * Math.sin(((_degree / 2) * Math.PI) / 180)}vw;
height: 45vw;
transform: rotate(${_degree * i + _degree / 2}deg);
transform-origin: 50% 100%;
`
}
})
// 获取随机数
const getRandomNum = () => {
const num = Math.floor(Math.random() * prizeList.length)
return num
}
const stopRun = () => {
isRunning = false
if (isLeaved) {
console.log('已经离开页面了,不用显示弹窗')
return
}
const prizeName = prizeList.find((e) => e.id === prizeId)!.name
uni.showModal({
title: `恭喜你中奖 ${prizeName}`,
success() {
styleObj.value = `${bgColor} transform: rotate(0deg);`
},
})
}
const startRun = () => {
console.log(isRunning, totalRunAngle.value)
// 设置动效
styleObj.value = `${bgColor} transform: rotate(${totalRunAngle.value}deg); transition: all 4s ease;`
setTimeout(stopRun, 4000)
}
const start = () => {
if (!isRunning) {
isRunning = true
console.log('开始抽奖,后台请求中奖奖品')
// 请求返回的奖品编号 这里使用随机数
prizeId = getRandomNum()
totalRunAngle.value = baseRunAngle - (prizeId + 0.5) * rotateAngle.value
console.log('中奖ID>>>', prizeId, prizeList[prizeId], totalRunAngle.value)
nextTick(() => {
startRun()
})
}
}
</script>
<style lang="scss">
.container {
position: relative;
width: 90vw;
height: 90vw;
margin: 20px auto;
border: 10px solid #98d3fc;
border-radius: 50%;
}
.prize-list {
box-sizing: border-box;
width: 100%;
height: 100%;
overflow: hidden;
border-radius: 50%;
// 使用outline代替border可以省很多定位的问题
// outline: 10px solid #98d3fc;
}
.prize-item {
position: absolute;
top: 0;
right: 0;
left: 0;
display: flex;
flex-direction: column;
margin: auto;
// border: 2px solid red;
}
.prize-item .gift-img {
display: block;
width: 30%;
height: 20%;
margin: 20px auto 10px;
border-radius: 50%;
}
.prize-item .gift-name {
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
}
.lottery-btn {
position: absolute;
top: 50%;
left: 50%;
width: 80px;
height: 96px;
margin: auto;
cursor: pointer;
background: url('https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/btn-enable.png')
no-repeat center / 100% 100%;
transform: translate(-50%, -50%);
}
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '九宫格抽奖' },
}
</route>
<template>
<view>
<view class="container">
<view
class="gift-item"
:class="{ active: currentIndex === index }"
v-for="(item, index) in prizeList"
:key="index"
@click="start(index)"
>
<image :src="item.pic" class="gift-img" />
<text v-if="index !== 4" class="gift-name">{{ item.name }}</text>
</view>
</view>
</view>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue'
let isLeaved = false
// onBackPress(({ from }: { from: 'backbutton' | 'navigateBack' }) => {
// console.log('onBackPress', from)
// isLeaved = true
// return false
// })
// onBackPress 有兼容性问题,统一使用 onUnload,测试验证OK
onUnload(() => {
isLeaved = true
console.log('onUnload', isLeaved)
})
const currentIndex = ref(0) // 当前位置
// 后台配置的奖品数据
const prizeList = [
{
id: 0,
name: '双肩包',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/backpack.jpeg',
},
{
id: 1,
name: '积木',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/jimu.jpg',
},
{
id: 2,
name: '红包',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/red-envelope.jpg',
},
{
id: 3,
name: '茶具',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/tea-set.jpg',
},
{
id: 5,
name: '可爱脸',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/tushetou.jpg',
},
{
id: 6,
name: '挖掘机',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/wajueji.jpg',
},
{
id: 7,
name: '无辜脸',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/xiaolian.jpg',
},
{
id: 8,
name: '烟灰缸',
pic: 'https://oss.laf.run/ukw0y1-site/hello-unibest-images/lottery/prizes/yanhuigang.jpg',
},
]
const startBtn = {
id: 4,
name: '开始按钮',
pic: 'https://img2.baidu.com/it/u=1497996119,382735686&fm=253',
}
// 九宫格中间位置插入开始按钮
prizeList.splice(4, 0, startBtn)
// 奖品高亮顺序
const prizeSort = [0, 1, 2, 5, 8, 7, 6, 3]
// 获取随机数
const getRandomNum = () => prizeSort[Math.floor(Math.random() * prizeSort.length)]
let isRunning = false // 是否正在抽奖
let speed = 10 // 抽奖转动速度
let timerIns = null // 定时器实例
let currentRunCount = 0 // 已跑次数
const totalRunCount = 32 // 总共跑动次数,8的倍数即可
let prizeId = 0 // 中奖id(0-8,不能是4)
// 要执行总步数
const totalRunStep = computed(() => {
return totalRunCount + prizeSort.indexOf(prizeId)
})
const stopRun = () => {
// eslint-disable-next-line no-unused-expressions
timerIns && clearTimeout(timerIns)
}
const startRun = () => {
stopRun()
console.log(currentRunCount, totalRunStep.value)
// 要执行总步数
// 已走步数超过
if (currentRunCount > totalRunStep.value) {
isRunning = false
if (isLeaved) {
console.log('已经离开页面了,不用显示弹窗')
return
}
const prizeName = prizeList.find((e) => e.id === prizeId)!.name
uni.showModal({
title: `恭喜你中奖 ${prizeName}`,
})
return
}
currentIndex.value = prizeSort[currentRunCount % 8]
// 如果当前步数超过了2/3则速度慢下来
if (currentRunCount > Math.floor((totalRunCount * 2) / 3)) {
speed += Math.floor(currentRunCount / 3)
console.log('速度>>>>', speed)
}
timerIns = setTimeout(() => {
currentRunCount++
startRun()
}, speed)
}
const start = (i) => {
if (i === 4 && !isRunning) {
// 重置数据
currentRunCount = 0
speed = 100
isRunning = true
console.log('开始抽奖,后台请求中奖奖品')
// 请求返回的奖品编号 这里使用随机数 但不能为4
// const prizeId = getRandomNum()
// console.log('中奖ID>>>', prizeId, prizeList[prizeId])
// prizeId = prizeId
// 模拟接口延时返回 如果接口突然报错如何处理?直接调用stopRun()方法停止转动
setTimeout(() => {
prizeId = getRandomNum()
console.log('中奖ID>>>', prizeId, prizeList[prizeId])
// 拿到数据才可以跑
}, 2000)
startRun()
}
}
</script>
<style lang="scss">
.container {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-around;
width: 90vw;
height: 90vw;
margin: 20px auto;
background: #98d3fc;
border: 1px solid #98d3fc;
}
.gift-item {
position: relative;
box-sizing: border-box;
width: 30vw;
height: 30vw;
border: 2px solid #fff;
}
.gift-item:nth-of-type(5) {
cursor: pointer;
}
.gift-item .gift-img {
width: 100%;
height: 100%;
}
.gift-item .gift-name {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 20px;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background: rgb(0 0 0 / 50%);
}
.active {
border: 2px solid red;
box-shadow: 2px 2px 30px #fff;
}
</style>
<route lang="json5">
{
layout: 'default',
style: { navigationBarTitleText: '签字板' },
}
</route>
<template>
<view class="canvas-box flex flex-col box-border p-3" :class="{ 'full-screen': isFullScreen }">
<canvas
canvas-id="canvas"
class="w-full b b-dashed b-rd b-gray-300 canvas"
:disable-scroll="true"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
@mousedown="touchStart"
@mousemove="touchMove"
@mouseup="touchEnd"
/>
<view class="btns flex justify-between text-center box-border">
<view class="btn-box flex">
<view class="btn bg-gray-100 b-rd b-gray-300 c-gray-500 p-1" @click="handFullScreen">
{{ isFullScreen ? '退出全屏' : '全屏' }}
</view>
<view class="btn bg-gray-100 b-rd b-gray-300 c-gray-500 p-1 ml-2" @click="clear">清空</view>
<view class="btn bg-gray-100 b-rd b-gray-300 c-gray-500 p-1 ml-2" @click="withdraw">
撤回
</view>
</view>
<view class="btn-box flex">
<view class="btn bg-sky-500 b-rd c-white p-1" @click="save">保存</view>
</view>
</view>
</view>
</template>
<script lang="ts" setup name="sign">
const isFullScreen = ref(false)
const isSigned = ref(false)
let ctx = null
let isButtonDown = false
let points = []
let allPoints = []
// 初始化画布
function initCanvas() {
ctx = uni.createCanvasContext('canvas')
// 设置画笔样式
ctx.lineWidth = 4
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
}
// 重设画板大小
function onResize() {
initCanvas() // 重新初始化canvas
}
// 绘画
function draw(w?) {
const point1 = points[0]
const point2 = points[1]
if (!w) {
allPoints[allPoints.length - 1].push(JSON.parse(JSON.stringify(points)))
}
points.shift()
ctx.moveTo(point1.X, point1.Y)
ctx.lineTo(point2.X, point2.Y)
ctx.stroke()
ctx.draw(true)
isSigned.value = true
}
// 触摸开始,获取到起点
function touchStart() {
allPoints.push([])
ctx.beginPath() // 每次触摸开始,开启新的路径
isButtonDown = true
}
// 触摸移动,获取到路径点
function touchMove(e) {
if (isButtonDown) {
let movePoint = {}
if (e.changedTouches[0].x) {
movePoint = { X: e.changedTouches[0].x, Y: e.changedTouches[0].y }
} else {
const X = e.changedTouches[0].pageX - e.currentTarget.offsetLeft
const Y = e.changedTouches[0].pageY - e.currentTarget.offsetTop
movePoint = { X, Y }
}
points.push(movePoint) // 存点
const len = points.length
if (len >= 2) {
draw() // 绘制路径
}
}
}
// 触摸结束,将未绘制的点清空防止对后续路径产生干扰
function touchEnd() {
allPoints = allPoints.filter((e) => {
return e.length > 0
})
points = []
isButtonDown = false
}
// 清空, 传入true表示清空全部,不传传表示撤回一步
function clear(reset?: boolean) {
if (reset) allPoints = []
ctx.clearRect(0, 0, 1000, 1000)
ctx.draw(true)
isSigned.value = false
}
// 全屏
function handFullScreen() {
clear(true)
isFullScreen.value = !isFullScreen.value
const tid = setTimeout(() => {
onResize()
clearTimeout(tid)
}, 100)
}
// 撤回
function withdraw() {
// 清除画布
clear()
if (allPoints.length <= 1) {
allPoints = []
points = []
return
}
// 删除最后一个路径
allPoints.pop()
// 循环路径,重新绘制
allPoints.forEach((e) => {
e.forEach((r) => {
points = JSON.parse(JSON.stringify(r))
draw(1)
})
})
}
// h5保存方法
function saveCanvasAsImage(dataURL, imageName?) {
// 创建一个Image元素
const img = new Image()
// 设置img的src属性为数据URL
img.src = dataURL
// 创建一个链接元素用于下载图片
const link = document.createElement('a')
// 设置下载的文件名
link.download = imageName || 'canvas-image'
// 触发点击,下载图片
link.href = img.src
link.click()
}
// 保存
const save = () => {
if (!isSigned.value) {
uni.showToast({
title: '请签名',
icon: 'none',
})
return
}
uni.canvasToTempFilePath({
canvasId: 'canvas',
success: (res) => {
// 获取图片路径
const { tempFilePath } = res
// 保存图片到相册
// #ifdef H5
const name = `sign-${new Date().getTime()}`
saveCanvasAsImage(tempFilePath, name)
// #endif
// #ifndef H5
uni.saveImageToPhotosAlbum({
filePath: tempFilePath,
success: () => {
uni.showToast({
title: '图片保存成功',
})
},
fail: (err) => {
console.error(err)
uni.showToast({
title: '图片保存失败',
icon: 'none',
})
},
})
// #endif
},
fail: () => {
uni.showToast({
title: '转换图片失败',
icon: 'none',
})
},
})
}
onMounted(() => {
initCanvas()
})
</script>
<style lang="scss" scoped>
$padding: 30rpx;
.canvas-box {
.canvas {
height: 300rpx;
transition: height 0.3s;
}
.btns {
margin-top: 10rpx;
transition: transform 0.3s;
.btn {
width: auto;
height: 50rpx;
}
}
}
.full-screen {
flex-direction: row;
height: calc(100vh - 88rpx);
.canvas {
width: calc(100% - 100rpx);
height: 100%;
margin-left: 100rpx;
}
.btns {
position: absolute;
align-items: center;
width: calc(100vh - (88rpx + $padding * 2));
height: 100rpx;
transform: translate(100rpx, 0) rotate(90deg);
transform-origin: top left;
.btn-box {
flex-direction: row;
}
}
}
</style>
<route lang="json5">
{
layout: 'demo',
style: { navigationBarTitleText: '富文本' },
}
</route>
<template>
<view class="home">
<view class="editor-box">
<sp-editor
:toolbar-config="{
excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
iconSize: '18px',
}"
@init="initEditor"
@input="inputOver"
@upinImage="upinImage"
@overMax="overMax"
@addLink="addLink"
@exportHtml="exportHtml"
></sp-editor>
</view>
</view>
</template>
<script setup>
import { ref } from 'vue'
const editorIns = ref(null)
/**
* 获取输入内容
* @param {Object} e {html,text} 内容的html文本,和text文本
*/
function inputOver(e) {
// 可以在此处获取到编辑器已编辑的内容
console.log('==== inputOver :', e)
}
/**
* 超出最大内容限制
* @param {Object} e {html,text} 内容的html文本,和text文本
*/
function overMax(e) {
// 若设置了最大字数限制,可在此处触发超出限制的回调
console.log('==== overMax :', e)
}
/**
* 编辑器就绪
* @param {Object} editor 编辑器实例,你可以自定义调用editor实例的方法
* @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
* @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
*/
function initEditor(editor) {
editorIns.value = editor // 保存编辑器实例
// 保存编辑器实例后,可以在此处获取后端数据,并赋值给编辑器初始化内容
preRender()
}
function preRender() {
setTimeout(() => {
// 异步获取后端数据后,初始化编辑器内容
editorIns.value.setContents({
html: `<div>&nbsp;&nbsp;猫猫<img src="https://img.yzcdn.cn/vant/cat.jpeg"/></div>`,
})
}, 1000)
}
/**
* 直接运行示例工程插入图片无法正常显示的看这里
* 因为插件默认采用云端存储图片的方式
* 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
* @param {Object} tempFiles
* @param {Object} editorCtx
*/
function upinImage(tempFiles, editorCtx) {
/**
* 本地临时插入图片预览
* 注意:这里仅是示例本地图片预览,因为需要将图片先上传到云端,再将图片插入到编辑器中
* 正式开发时,还请将此处注释,并解开下面 使用 uniCloud.uploadFile 上传图片的示例方法 的注释
* @tutorial https://uniapp.dcloud.net.cn/api/media/editor-context.html#editorcontext-insertimage
*/
// #ifdef MP-WEIXIN
// 注意微信小程序的图片路径是在tempFilePath字段中
editorCtx.insertImage({
src: tempFiles[0].tempFilePath,
width: '80%', // 默认不建议铺满宽度100%,预留一点空隙以便用户编辑
success: function () {},
})
// #endif
// #ifndef MP-WEIXIN
editorCtx.insertImage({
src: tempFiles[0].path,
width: '80%', // 默认不建议铺满宽度100%,预留一点空隙以便用户编辑
success: function () {},
})
// #endif
/**
* 使用 uniCloud.uploadFile 上传图片的示例方法(可适用多选上传)
* 正式开发环境中,请将上面 本地临时插入图片预览 注释后,模仿以下写法
*/
// tempFiles.forEach(async (item) => {
// uni.showLoading({
// title: '上传中请稍后',
// mask: true
// })
// let upfile = await uniCloud.uploadFile({
// filePath: item.path,
// // 同名会导致报错 policy_does_not_allow_file_overwrite
// // cloudPath可由 想要存储的文件夹/文件名 拼接,若不拼文件夹名则默认存储在cloudstorage文件夹中
// cloudPath: `cloudstorage/${item.name}`,
// cloudPathAsRealPath: true
// })
// editorCtx.insertImage({
// src: upfile.fileID,
// width: '80%', // 默认不建议铺满宽度100%,预留一点空隙以便用户编辑
// success: function () {
// uni.hideLoading()
// }
// })
// })
}
/**
* 导出 - toolbar需要开启export工具
* @param {string} e 导出的html内容
*/
function exportHtml(e) {
uni.navigateTo({
url: '/pages/out/out',
success(res) {
// 传至导出页面解析即可
res.eventChannel.emit('e-transmit-html', {
data: e,
})
},
})
}
/**
* 添加超链接
* @param {Object} e { text: '链接描述', href: '链接地址' }
*/
function addLink(e) {
console.log('==== addLink :', e)
}
</script>
{
"localdata": [
{ "value": 35, "text": "2016", "group": "目标值" },
{ "value": 18, "text": "2016", "group": "完成量" },
{ "value": 36, "text": "2017", "group": "目标值" },
{ "value": 27, "text": "2017", "group": "完成量" },
{ "value": 31, "text": "2018", "group": "目标值" },
{ "value": 21, "text": "2018", "group": "完成量" },
{ "value": 33, "text": "2019", "group": "目标值" },
{ "value": 24, "text": "2019", "group": "完成量" },
{ "value": 13, "text": "2020", "group": "目标值" },
{ "value": 6, "text": "2020", "group": "完成量" },
{ "value": 34, "text": "2021", "group": "目标值" },
{ "value": 28, "text": "2021", "group": "完成量" }
],
"localdataB": [
{ "value": 50, "text": "一班" },
{ "value": 30, "text": "二班" },
{ "value": 20, "text": "三班" },
{ "value": 18, "text": "四班" },
{ "value": 8, "text": "五班" }
],
"TLine": {
"series": [
{
"name": "时间轴1",
"data": [
[10000, 55],
[30000, 25],
[50000, 55],
[70000, 25],
[90000, 55]
]
},
{
"name": "时间轴2",
"data": [
[0, 25],
[20000, 55],
[40000, 25],
[60000, 55],
[80000, 25]
]
},
{
"name": "时间轴3",
"data": [
[0, 55],
[15000, 25],
[30000, 55],
[45000, 25],
[60000, 55]
]
}
]
},
"Scatter": {
"series": [
{
"name": "散点一",
"data": [
[10.0, 8.04],
[8.07, 6.95],
[13.0, 7.58],
[9.05, 8.81],
[11.0, 8.33],
[14.0, 7.66],
[13.4, 6.81],
[10.0, 6.33],
[14.0, 8.96],
[12.5, 6.82]
]
},
{
"name": "散点二",
"data": [
[9.15, 7.2],
[11.5, 7.2],
[3.03, 4.23],
[12.2, 7.83],
[2.02, 4.47],
[1.05, 3.33],
[4.05, 4.96],
[6.03, 7.24],
[12.0, 6.26],
[12.0, 8.84],
[7.08, 5.82],
[5.02, 5.68]
]
}
]
},
"Bubble": {
"series": [
{
"name": "气泡一",
"data": [
[95, 95, 23, "标题1"],
[30, 55, 33, "标题2"]
]
},
{
"name": "气泡二",
"data": [
[130, 30, 30, "标题3"],
[200, 90, 40, "标题4"]
]
}
]
},
"Column": {
"categories": ["2016", "2017", "2018", "2019", "2020", "2021"],
"series": [
{
"name": "目标值",
"data": [35, 36, 31, 33, 13, 34]
},
{
"name": "完成量",
"data": [18, 27, 21, 24, 6, 28]
}
]
},
"ColumnA": {
"categories": ["2016", "2017", "2018", "2019", "2020", "2021"],
"series": [
{
"name": "成交量1",
"data": [15, { "value": 20, "color": "#f04864" }, 45, 37, 43, 34]
},
{
"name": "成交量2",
"data": [30, { "value": 40, "color": "#facc14" }, 25, 14, 34, 18]
}
]
},
"Mix": {
"categories": ["2016", "2017", "2018", "2019", "2020", "2021"],
"series": [
{
"name": "曲面",
"data": [70, 50, 85, 130, 64, 88],
"type": "area",
"style": "curve"
},
{
"name": "柱1",
"index": 1,
"data": [40, { "value": 30, "color": "#f04864" }, 55, 110, 24, 58],
"type": "column"
},
{
"name": "柱2",
"index": 1,
"data": [50, 20, 75, 60, 34, 38],
"type": "column"
},
{
"name": "曲线",
"data": [70, 50, 85, 130, 64, 88],
"type": "line",
"style": "curve",
"color": "#1890ff",
"disableLegend": true
},
{
"name": "折线",
"data": [120, 140, 105, 170, 95, 160],
"type": "line",
"color": "#2fc25b"
},
{
"name": "点",
"index": 2,
"data": [100, 80, 125, 150, 112, 132],
"type": "point",
"color": "#f04864"
}
]
},
"Line": {
"categories": ["2016", "2017", "2018", "2019", "2020", "2021"],
"series": [
{
"name": "成交量A",
"data": [35, 8, 25, 37, 4, 20]
},
{
"name": "成交量B",
"data": [70, 40, 65, 100, 44, 68]
},
{
"name": "成交量C",
"data": [100, 80, 95, 150, 112, 132]
}
]
},
"Pie": {
"series": [
{
"name": "一班",
"data": 50
},
{
"name": "二班",
"data": 30
},
{
"name": "三班",
"data": 20
},
{
"name": "四班",
"data": 18
},
{
"name": "五班",
"data": 8
}
]
},
"PieA": {
"series": [
{
"data": [
{
"name": "一班",
"value": 50
},
{
"name": "二班",
"value": 30
},
{
"name": "三班",
"value": 20
},
{
"name": "四班",
"value": 18
},
{
"name": "五班",
"value": 8
}
]
}
]
},
"Mount": {
"series": [
{
"data": [
{
"name": "一班",
"value": 82
},
{
"name": "二班",
"value": 63
},
{
"name": "三班",
"value": 86
},
{
"name": "四班",
"value": 65
},
{
"name": "五班",
"value": 79
}
]
}
]
},
"Radar": {
"categories": ["维度1", "维度2", "维度3", "维度4", "维度5", "维度6"],
"series": [
{
"name": "成交量1",
"data": [90, 110, 165, 195, 187, 172]
},
{
"name": "成交量2",
"data": [190, 210, 105, 35, 27, 102]
}
]
},
"Arcbar1": {
"series": [
{
"name": "正确率",
"data": 0.8,
"color": "#2fc25b"
}
]
},
"Arcbar2": {
"series": [
{
"name": "一班",
"data": 0.8
},
{
"name": "二班",
"data": 0.6
},
{
"name": "三班",
"data": 0.45
},
{
"name": "四班",
"data": 0.3
},
{
"name": "五班",
"data": 0.15
}
]
},
"Gauge": {
"categories": [
{
"value": 0.2,
"color": "#1890ff"
},
{
"value": 0.8,
"color": "#2fc25b"
},
{
"value": 1,
"color": "#f04864"
}
],
"series": [
{
"name": "完成率",
"data": 0.66
}
]
},
"Candle": {
"categories": [
"2020/1/24",
"2020/1/25",
"2020/1/28",
"2020/1/29",
"2020/1/30",
"2020/1/31",
"2020/2/1",
"2020/2/4",
"2020/2/5",
"2020/2/6",
"2020/2/7",
"2020/2/8",
"2020/2/18",
"2020/2/19",
"2020/2/20",
"2020/2/21",
"2020/2/22",
"2020/2/25",
"2020/2/26",
"2020/2/27",
"2020/2/28",
"2020/3/1",
"2020/3/4",
"2020/3/5",
"2020/3/6",
"2020/3/7",
"2020/3/8",
"2020/3/11",
"2020/3/12",
"2020/3/13",
"2020/3/14",
"2020/3/15",
"2020/3/18",
"2020/3/19",
"2020/3/20",
"2020/3/21",
"2020/3/22",
"2020/3/25",
"2020/3/26",
"2020/3/27",
"2020/3/28",
"2020/3/29",
"2020/4/1",
"2020/4/2",
"2020/4/3",
"2020/4/8",
"2020/4/9",
"2020/4/10",
"2020/4/11",
"2020/4/12",
"2020/4/15",
"2020/4/16",
"2020/4/17",
"2020/4/18",
"2020/4/19",
"2020/4/22",
"2020/4/23",
"2020/4/24",
"2020/4/25",
"2020/4/26",
"2020/5/2",
"2020/5/3",
"2020/5/6",
"2020/5/7",
"2020/5/8",
"2020/5/9",
"2020/5/10",
"2020/5/13",
"2020/5/14",
"2020/5/15",
"2020/5/16",
"2020/5/17",
"2020/5/20",
"2020/5/21",
"2020/5/22",
"2020/5/23",
"2020/5/24",
"2020/5/27",
"2020/5/28",
"2020/5/29",
"2020/5/30",
"2020/5/31",
"2020/6/3",
"2020/6/4",
"2020/6/5",
"2020/6/6",
"2020/6/7",
"2020/6/13"
],
"series": [
{
"name": "上证指数",
"data": [
[2320.26, 2302.6, 2287.3, 2362.94],
[2300, 2291.3, 2288.26, 2308.38],
[2295.35, 2346.5, 2295.35, 2346.92],
[2347.22, 2358.98, 2337.35, 2363.8],
[2360.75, 2382.48, 2347.89, 2383.76],
[2383.43, 2385.42, 2371.23, 2391.82],
[2377.41, 2419.02, 2369.57, 2421.15],
[2425.92, 2428.15, 2417.58, 2440.38],
[2411, 2433.13, 2403.3, 2437.42],
[2432.68, 2434.48, 2427.7, 2441.73],
[2430.69, 2418.53, 2394.22, 2433.89],
[2416.62, 2432.4, 2414.4, 2443.03],
[2441.91, 2421.56, 2415.43, 2444.8],
[2420.26, 2382.91, 2373.53, 2427.07],
[2383.49, 2397.18, 2370.61, 2397.94],
[2378.82, 2325.95, 2309.17, 2378.82],
[2322.94, 2314.16, 2308.76, 2330.88],
[2320.62, 2325.82, 2315.01, 2338.78],
[2313.74, 2293.34, 2289.89, 2340.71],
[2297.77, 2313.22, 2292.03, 2324.63],
[2322.32, 2365.59, 2308.92, 2366.16],
[2364.54, 2359.51, 2330.86, 2369.65],
[2332.08, 2273.4, 2259.25, 2333.54],
[2274.81, 2326.31, 2270.1, 2328.14],
[2333.61, 2347.18, 2321.6, 2351.44],
[2340.44, 2324.29, 2304.27, 2352.02],
[2326.42, 2318.61, 2314.59, 2333.67],
[2314.68, 2310.59, 2296.58, 2320.96],
[2309.16, 2286.6, 2264.83, 2333.29],
[2282.17, 2263.97, 2253.25, 2286.33],
[2255.77, 2270.28, 2253.31, 2276.22],
[2269.31, 2278.4, 2250, 2312.08],
[2267.29, 2240.02, 2239.21, 2276.05],
[2244.26, 2257.43, 2232.02, 2261.31],
[2257.74, 2317.37, 2257.42, 2317.86],
[2318.21, 2324.24, 2311.6, 2330.81],
[2321.4, 2328.28, 2314.97, 2332],
[2334.74, 2326.72, 2319.91, 2344.89],
[2318.58, 2297.67, 2281.12, 2319.99],
[2299.38, 2301.26, 2289, 2323.48],
[2273.55, 2236.3, 2232.91, 2273.55],
[2238.49, 2236.62, 2228.81, 2246.87],
[2229.46, 2234.4, 2227.31, 2243.95],
[2234.9, 2227.74, 2220.44, 2253.42],
[2232.69, 2225.29, 2217.25, 2241.34],
[2196.24, 2211.59, 2180.67, 2212.59],
[2215.47, 2225.77, 2215.47, 2234.73],
[2224.93, 2226.13, 2212.56, 2233.04],
[2236.98, 2219.55, 2217.26, 2242.48],
[2218.09, 2206.78, 2204.44, 2226.26],
[2199.91, 2181.94, 2177.39, 2204.99],
[2169.63, 2194.85, 2165.78, 2196.43],
[2195.03, 2193.8, 2178.47, 2197.51],
[2181.82, 2197.6, 2175.44, 2206.03],
[2201.12, 2244.64, 2200.58, 2250.11],
[2236.4, 2242.17, 2232.26, 2245.12],
[2242.62, 2184.54, 2182.81, 2242.62],
[2187.35, 2218.32, 2184.11, 2226.12],
[2213.19, 2199.31, 2191.85, 2224.63],
[2203.89, 2177.91, 2173.86, 2210.58],
[2170.78, 2174.12, 2161.14, 2179.65],
[2179.05, 2205.5, 2179.05, 2222.81],
[2212.5, 2231.17, 2212.5, 2236.07],
[2227.86, 2235.57, 2219.44, 2240.26],
[2242.39, 2246.3, 2235.42, 2255.21],
[2246.96, 2232.97, 2221.38, 2247.86],
[2228.82, 2246.83, 2225.81, 2247.67],
[2247.68, 2241.92, 2231.36, 2250.85],
[2238.9, 2217.01, 2205.87, 2239.93],
[2217.09, 2224.8, 2213.58, 2225.19],
[2221.34, 2251.81, 2210.77, 2252.87],
[2249.81, 2282.87, 2248.41, 2288.09],
[2286.33, 2299.99, 2281.9, 2309.39],
[2297.11, 2305.11, 2290.12, 2305.3],
[2303.75, 2302.4, 2292.43, 2314.18],
[2293.81, 2275.67, 2274.1, 2304.95],
[2281.45, 2288.53, 2270.25, 2292.59],
[2286.66, 2293.08, 2283.94, 2301.7],
[2293.4, 2321.32, 2281.47, 2322.1],
[2323.54, 2324.02, 2321.17, 2334.33],
[2316.25, 2317.75, 2310.49, 2325.72],
[2320.74, 2300.59, 2299.37, 2325.53],
[2300.21, 2299.25, 2294.11, 2313.43],
[2297.1, 2272.42, 2264.76, 2297.1],
[2270.71, 2270.93, 2260.87, 2276.86],
[2264.43, 2242.11, 2240.07, 2266.69],
[2242.26, 2210.9, 2205.07, 2250.63],
[2190.1, 2148.35, 2126.22, 2190.1]
]
}
]
},
"CandleColumn": {
"categories": [
"2020/1/24",
"2020/1/25",
"2020/1/28",
"2020/1/29",
"2020/1/30",
"2020/1/31",
"2020/2/1",
"2020/2/4",
"2020/2/5",
"2020/2/6",
"2020/2/7",
"2020/2/8",
"2020/2/18",
"2020/2/19",
"2020/2/20",
"2020/2/21",
"2020/2/22",
"2020/2/25",
"2020/2/26",
"2020/2/27",
"2020/2/28",
"2020/3/1",
"2020/3/4",
"2020/3/5",
"2020/3/6",
"2020/3/7",
"2020/3/8",
"2020/3/11",
"2020/3/12",
"2020/3/13",
"2020/3/14",
"2020/3/15",
"2020/3/18",
"2020/3/19",
"2020/3/20",
"2020/3/21",
"2020/3/22",
"2020/3/25",
"2020/3/26",
"2020/3/27",
"2020/3/28",
"2020/3/29",
"2020/4/1",
"2020/4/2",
"2020/4/3",
"2020/4/8",
"2020/4/9",
"2020/4/10",
"2020/4/11",
"2020/4/12",
"2020/4/15",
"2020/4/16",
"2020/4/17",
"2020/4/18",
"2020/4/19",
"2020/4/22",
"2020/4/23",
"2020/4/24",
"2020/4/25",
"2020/4/26",
"2020/5/2",
"2020/5/3",
"2020/5/6",
"2020/5/7",
"2020/5/8",
"2020/5/9",
"2020/5/10",
"2020/5/13",
"2020/5/14",
"2020/5/15",
"2020/5/16",
"2020/5/17",
"2020/5/20",
"2020/5/21",
"2020/5/22",
"2020/5/23",
"2020/5/24",
"2020/5/27",
"2020/5/28",
"2020/5/29",
"2020/5/30",
"2020/5/31",
"2020/6/3",
"2020/6/4",
"2020/6/5",
"2020/6/6",
"2020/6/7",
"2020/6/13"
],
"series": [
{
"name": "成交量1",
"data": [
15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20,
45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37,
43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15,
20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45, 37, 43, 15, 20, 45
]
}
]
},
"Word": {
"series": [
{
"name": "跨全端图表",
"textSize": 25
},
{
"name": "微信小程序",
"textSize": 20
},
{
"name": "支付宝小程序",
"textSize": 20
},
{
"name": "百度小程序",
"textSize": 20
},
{
"name": "QQ小程序",
"textSize": 20
},
{
"name": "头条小程序",
"textSize": 20
},
{
"name": "抖音小程序",
"textSize": 20
},
{
"name": "360小程序",
"textSize": 20
},
{
"name": "跨全端",
"textSize": 10
},
{
"name": "跨全端",
"textSize": 12
},
{
"name": "跨全端",
"textSize": 10
},
{
"name": "跨全端",
"textSize": 12
},
{
"name": "跨全端",
"textSize": 10
},
{
"name": "跨全端",
"textSize": 12
},
{
"name": "跨全端",
"textSize": 10
},
{
"name": "跨全端",
"textSize": 12
}
]
}
}
<route lang="json5" type="page">
{
style: { navigationBarTitleText: 'ucharts 图表' },
}
</route>
<template>
<view class="content">
<qiun-title-bar title="tooltip提示窗format" />
<view class="charts-box">
<!-- 注意:因app端通过组件均不能传递function类型参数,组件内所有formatter方法,均需使用format属性指定config-echarts.js里事先定义好的formatter的key值,组件会自动匹配与其对应的function -->
<!-- tooltip的format需要在组件的props参数上传递,例如tooltipFormat="tooltipDemo1",并需要在config-echarts.js中的formatter节点中的tooltipDemo1中配置format方法。如果开启了echarts,则需要在config-echarts.js中的formatter节点中的tooltipDemo1中配置format方法。 -->
<qiun-data-charts
type="column"
:echartsH5="true"
:echartsApp="true"
:chartData="chartsDataLine1"
tooltipFormat="tooltipDemo1"
/>
</view>
<qiun-title-bar title="图例的format" />
<view class="charts-box">
<!-- 需要把echarts文档内的formatter转成format,对应的'legendFormat'这个字符串为config-echarts.js中的formatter节点中的 legendFormat 方法-->
<qiun-data-charts
type="line"
:echartsH5="true"
:echartsApp="true"
:eopts="{ legend: { format: 'legendFormat' } }"
:chartData="chartsDataColumn2"
/>
</view>
<qiun-title-bar title="Y轴format方式1" />
<view class="charts-box">
<!-- 需要把echarts文档内的formatter转成format,对应的'yAxisFormatDemo'这个字符串为config-echarts.js中的formatter节点中的 yAxisFormatDemo 方法-->
<qiun-data-charts
type="line"
:echartsH5="true"
:echartsApp="true"
:eopts="{ yAxis: { axisLabel: { format: 'yAxisFormatDemo' } } }"
:chartData="chartsDataLine1"
/>
</view>
<qiun-title-bar title="Y轴format方式2" />
<view class="charts-box">
<!-- ECharts如果使用 formatter,则只能使用字符串模板方式,不能使用函数模板!函数模板请参考上面的例子-->
<qiun-data-charts
type="line"
:echartsH5="true"
:echartsApp="true"
:eopts="{ yAxis: { axisLabel: { formatter: '{value} 元' } } }"
:chartData="chartsDataLine1"
/>
</view>
<qiun-title-bar title="series数据点format方法1" />
<view class="charts-box">
<!-- seriesTemplate是config-echarts.js中对应图表类型定义好的series模板 ,如果每个series的formatter都不一样,则format需要定义在chartData.series中,不能使用seriesTemplate -->
<!-- formatter需要把echarts文档内的formatter转成format,对应的'seriesFormatDemo'这个字符串为config-echarts.js中的formatter节点中的 seriesFormatDemo 方法-->
<qiun-data-charts
type="line"
:echartsH5="true"
:echartsApp="true"
:eopts="{ seriesTemplate: { label: { format: 'seriesFormatDemo' } } }"
:chartData="chartsDataLine1"
/>
</view>
<qiun-title-bar title="series数据点format方法2" />
<view class="charts-box">
<!-- ECharts如果使用 formatter,则只能使用字符串模板方式,不能使用函数模板!函数模板请参考上面的例子-->
<qiun-data-charts
type="line"
:echartsH5="true"
:echartsApp="true"
:eopts="{ seriesTemplate: { label: { formatter: '{b}年{c}元' } } }"
:chartData="chartsDataLine1"
/>
</view>
</view>
</template>
<script>
// 下面是演示数据,您的项目不需要引用,数据需要您从服务器自行获取
import demodata from './data.json'
export default {
data() {
return {
chartsDataLine1: {},
chartsDataColumn2: {},
}
},
onLoad() {
// 模拟从服务器获取数据
this.getServerData()
},
methods: {
getServerData() {
setTimeout(() => {
// 因部分数据格式一样,这里不同图表引用同一数据源的话,需要深拷贝一下构造不同的对象
// 开发者需要自行处理服务器返回的数据,应与标准数据格式一致,注意series的data数值应为数字格式
this.chartsDataLine1 = JSON.parse(JSON.stringify(demodata.Line))
this.chartsDataColumn2 = JSON.parse(JSON.stringify(demodata.Column))
}, 1500)
},
},
}
</script>
<style>
.content {
display: flex;
flex: 1;
flex-direction: column;
}
.charts-box {
width: 100%;
height: 300px;
}
</style>
<route lang="json5" type="page">
{
style: { navigationBarTitleText: 'waterfall' },
}
</route>
<template>
<view class="waterfall">
<uv-waterfall
ref="waterfall"
v-model="list"
:add-time="10"
:left-gap="leftGap"
:right-gap="rightGap"
:column-gap="columnGap"
@changeList="changeList"
>
<!-- 第一列数据 -->
<template v-slot:list1>
<!-- 为了磨平部分平台的BUG,必须套一层view -->
<view>
<view v-for="item in lists.list1" :key="item.id" class="waterfall-item">
<view class="waterfall-item__image" :style="[imageStyle(item)]">
<image
:src="item.image"
mode="widthFix"
:style="{ width: item.width + 'px' }"
></image>
</view>
<view class="waterfall-item__ft">
<view class="waterfall-item__ft__title">
<text class="value">{{ item.title }}</text>
</view>
<view class="waterfall-item__ft__desc uv-line-2">
<text class="value">{{ item.desc }}</text>
</view>
</view>
</view>
</view>
</template>
<!-- 第二列数据 -->
<template v-slot:list2>
<!-- 为了磨平部分平台的BUG,必须套一层view -->
<view>
<view v-for="item in lists.list2" :key="item.id" class="waterfall-item">
<view class="waterfall-item__image" :style="[imageStyle(item)]">
<image
:src="item.image"
mode="widthFix"
:style="{ width: item.width + 'px' }"
></image>
</view>
<view class="waterfall-item__ft">
<view class="waterfall-item__ft__title">
<text class="value">{{ item.title }}</text>
</view>
<view class="waterfall-item__ft__desc uv-line-2">
<text class="value">{{ item.desc }}</text>
</view>
</view>
</view>
</view>
</template>
</uv-waterfall>
</view>
</template>
<script lang="ts" setup>
const list = ref([]) // 瀑布流全部数据
const lists = reactive({
list1: [], // 瀑布流第一列数据
list2: [], // 瀑布流第二列数据
})
const leftGap = ref(10)
const rightGap = ref(10)
const columnGap = ref(10)
const imageStyle = computed(() => {
return (item) => {
const v = uni.upx2px(750) - leftGap.value - rightGap.value - columnGap.value
const w = v / 2
const rate = w / item.w
const h = rate * item.h
return {
width: `${w}px`,
height: `${h}px`,
}
}
})
onLoad(async () => {
const { data } = await getData()
list.value = data
})
const waterfall = ref()
// 如果页面还没渲染结束,页面就跳走,但此时@changeList回调还在返回数据,可能会造成渲染出错,所以要想办法停止渲染
onHide(() => {
waterfall.value.clear()
})
// 这点非常重要:e.name在这里返回是list1或list2,要手动将数据追加到相应列
const changeList = (e: { name: 'list1' | 'list2'; value: any }) => {
lists[e.name].push(e.value)
}
// 模拟的后端数据6
const getData = (): Promise<{ data: any[] }> => {
return new Promise((resolve) => {
const imgs = [
{ url: 'https://via.placeholder.com/100x110.png/3c9cff/fff', width: 100, height: 110 },
{ url: 'https://via.placeholder.com/200x220.png/f9ae3d/fff', width: 200, height: 220 },
{ url: 'https://via.placeholder.com/300x340.png/5ac725/fff', width: 300, height: 340 },
{ url: 'https://via.placeholder.com/400x400.png/f56c6c/fff', width: 400, height: 400 },
{ url: 'https://via.placeholder.com/500x510.png/909399/fff', width: 500, height: 510 },
{ url: 'https://via.placeholder.com/600x606.png/3c9cff/fff', width: 600, height: 606 },
{ url: 'https://via.placeholder.com/310x422.png/f1a532/fff', width: 310, height: 422 },
{ url: 'https://via.placeholder.com/320x430.png/3c9cff/fff', width: 320, height: 430 },
{ url: 'https://via.placeholder.com/330x424.png/f9ae3d/fff', width: 330, height: 424 },
{ url: 'https://via.placeholder.com/340x435.png/5ac725/fff', width: 340, height: 435 },
{ url: 'https://via.placeholder.com/350x440.png/f56c6c/fff', width: 350, height: 440 },
{ url: 'https://via.placeholder.com/380x470.png/909399/fff', width: 380, height: 470 },
]
const arr = []
const doFn = (i: number) => {
const randomIndex = Math.floor(Math.random() * 10)
return {
id: uni.$uv.guid(),
allowEdit: i === 0,
image: imgs[randomIndex].url,
w: imgs[randomIndex].width,
h: imgs[randomIndex].height,
title:
i % 2 === 0
? `(${list.value.length + i + 1})体验uv-ui框架`
: `(${list.value.length + i + 1})uv-ui支持多平台`,
desc:
i % 2 === 0
? `(${list.value.length + i + 1})欢迎使用uv-ui,uni-app生态专用的UI框架`
: `(${list.value.length + i})开发者编写一套代码, 可发布到iOS、Android、H5、以及各种小程序`,
}
}
// 模拟异步
setTimeout(() => {
for (let i = 0; i < 20; i++) {
arr.push(doFn(i))
}
resolve({ data: arr })
}, 200)
})
}
</script>
<style>
page {
background: #f1f1f1;
}
</style>
<style lang="scss" scoped>
.waterfall-item {
margin-top: 10px;
overflow: hidden;
border-radius: 6px;
/* stylelint-disable-next-line selector-class-pattern */
.waterfall-item__ft {
padding: 20rpx;
background: #fff;
&__title {
margin-bottom: 10rpx;
font-weight: 700;
line-height: 48rpx;
.value {
font-size: 32rpx;
color: #303133;
}
}
&__desc .value {
font-size: 28rpx;
color: #606266;
}
&__btn {
padding: 10px 0;
}
}
}
</style>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: 'z-paging',
},
}
</route>
<template>
<z-paging ref="paging" v-model="dataList" @query="queryList">
<view class="item" v-for="(item, index) in dataList" :key="index">
<view class="item-title">{{ item }}</view>
</view>
</z-paging>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { getList } from '@/service/foo'
const paging = ref(null)
const dataList = ref([])
const queryList = (pageNo?: number, pageSize?: number) => {
// 这里的pageNo和pageSize会自动计算好,直接传给服务器即可
// 这里的请求只是演示,请替换成自己的项目的网络请求,并在网络请求回调中通过paging.value.complete(请求回来的数组)将请求结果传给z-paging
getList(pageNo, pageSize)
.then((res) => {
// 请勿在网络请求回调中给dataList赋值!!只需要调用complete就可以了
console.log(res)
paging.value.complete(res.data.list)
})
.catch((res) => {
// 如果请求失败写paging.value.complete(false),会自动展示错误页面
// 注意,每次都需要在catch中写这句话很麻烦,z-paging提供了方案可以全局统一处理
// 在底层的网络请求抛出异常时,写uni.$emit('z-paging-error-emit');即可
paging.value.complete(false)
})
}
onLoad(() => {
queryList()
})
</script>
<style scoped></style>
<route lang="json5" type="page">
{
style: { navigationBarTitleText: '登陆拦截' },
}
</route>
<template>
<view class="mt-8 text-center p-4">
<view class="">登陆拦截的时候的登录有如下3种情况</view>
<view class="">1.登录动作有单独的登录页面,需要通过重定向处理</view>
<view class="">
2.登录动作在当前页面通过弹窗登录,登录后需要更新登录状态(或者刷新本页面,体验没那么好)
</view>
<view class="">3.静默登录,小程序可以直接login,通常情况下都是登录状态的</view>
<view class="leading-10">
用户是否已登录:
<text>{{ isLogined ? '是' : '否' }}</text>
</view>
<button v-if="!isLogined" @click="setUserInfo" class="mt-4" type="primary">登陆</button>
<button v-else @click="clearUserInfo" class="mt-4" type="warn">登出</button>
<button class="mt-8" @click="testAt">测试 Array.prototype.at</button>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store'
const userStore = useUserStore()
const isLogined = computed(() => {
return userStore.isLogined
})
const setUserInfo = () => {
userStore.setUserInfo({ nickname: '菲鸽', avatar: '', token: 'abcdef' })
}
const clearUserInfo = () => {
userStore.clearUserInfo()
}
const testAt = () => {
console.log('Array.prototype.at typeof: ', typeof Array.prototype.at)
}
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
layout: 'default',
style: {
navigationBarTitleText: '自动登录(无需拦截)',
},
}
</route>
<template>
<view class="mt-8 text-center p-4">
<view class="">
自动登录,通常在小程序里面都会先自动登录,所以都是登录状态,无需拦截。这个项目不方便演示,后续开个新项目演示
</view>
</view>
</template>
<script lang="ts" setup>
//
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
style: { navigationBarTitleText: '登陆拦截 - 登陆弹窗' },
}
</route>
<template>
<view class="mt-8 text-center p-4">
<view class="leading-10">
用户是否已登录:
<text>{{ isLogined ? '是' : '否' }}</text>
</view>
<view>这里有一个按钮(比如点赞按钮),点击这个按钮需要先登录</view>
<button type="primary" @tap="onClick" class="mt-4">点赞菲鸽</button>
<uv-modal
ref="modal"
title="登陆"
content="模拟登陆,点击确认按钮即可"
@confirm="confirmLogin"
></uv-modal>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
const userStore = useUserStore()
const pages = getCurrentPages()
console.log('pages:', pages)
const modal = ref()
const isLogined = computed(() => {
console.log('userStore=>', userStore)
const pages = getCurrentPages()
console.log('pages:', pages)
return userStore.isLogined
})
const confirmLogin = () => {
userStore.setUserInfo({ nickname: '菲鸽', avatar: '', token: 'abcdef' })
onClick() // 补偿机制,比较友好。当然,也可以让用户重新点击一下。
modal.value?.close()
}
const onClick = () => {
if (isLogined.value) {
console.log('用户已登录,可以点赞')
uni.showToast({ title: '点赞成功' })
// 这里执行接口请求
return
}
modal.value?.open()
}
/** 激活“分享给好友” */
onShareAppMessage((options: Page.ShareAppMessageOption): Page.CustomShareContent => {
console.log('options:', options)
return {
title: 'unibest 路由拦截、进入指定页面',
desc: 'unibest 演示示例',
// path: '/pages/demo/base/route-middleware?redirect=/pages/demo/base/route-interceptor?a=1&b=2',
path: 'pages/route-interceptor/index?name=feige&age=30&sex=male',
}
})
/** 激活“分享到朋友圈”, 注意:需要先激活“分享给好友” */
onShareTimeline((): Page.ShareTimelineContent => {
return {
title: '自定义分享标题',
query: 'a=1&b=2',
}
})
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5" type="page">
{
needLogin: true,
style: { navigationBarTitleText: '登陆拦截 - 登陆页面' },
}
</route>
<template>
<view class="mt-8 text-center p-4">
<view class="leading-10">
用户是否已登录:
<text>{{ isLogined ? '是' : '否' }}</text>
</view>
<view class="text-gray">未登录不能来本页面</view>
<view class="text-gray">已登录才能来本页面</view>
<view class="text-gray">增加微信分享功能,方便测试路由拦截</view>
</view>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getLastItem } from '@/utils'
const userStore = useUserStore()
const pages = getCurrentPages()
console.log('pages:', pages)
const isLogined = computed(() => {
console.log('userStore=>', userStore)
const pages = getCurrentPages()
console.log('pages:', pages)
return userStore.isLogined
})
// TODO Check
const loginRoute = '/pages/login/index'
onLoad((opt) => {
console.log('onLoad', isLogined.value, opt)
})
onReady(() => {
const pages = getCurrentPages()
const lastPage = getLastItem(pages)
console.log('route-interception.vue onReady last page:', isLogined.value, lastPage)
const currRoute = (lastPage as any).$page
console.log('route-interception.vue onReady currRoute:', currRoute)
if (!isLogined.value) {
// redirect时都需要 encodeURIComponent 一下,否则获取到的参数不对
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currRoute.fullPath)}`
uni.redirectTo({ url: redirectRoute })
}
})
/** 激活“分享给好友” */
onShareAppMessage((options: Page.ShareAppMessageOption): Page.CustomShareContent => {
console.log('options:', options)
return {
title: 'unibest 路由拦截、进入指定页面',
desc: 'unibest 演示示例',
// path: '/pages/demo/base/route-middleware?redirect=/pages/demo/base/route-interceptor?a=1&b=2',
path: 'pages/route-interceptor/index?name=feige&age=30&sex=male',
}
})
/** 激活“分享到朋友圈”, 注意:需要先激活“分享给好友” */
onShareTimeline((): Page.ShareTimelineContent => {
return {
title: '自定义分享标题',
query: 'a=1&b=2',
}
})
</script>
<style lang="scss" scoped>
//
</style>
<!-- 使用 type="home" 属性设置首页,其他页面不需要设置,默认为page;推荐使用json5,更强大,且允许注释 -->
<route lang="json5" type="home">
{
style: {
navigationStyle: 'custom',
navigationBarTitleText: '首页',
},
}
</route>
<template>
<view
class="bg-white overflow-hidden pt-2 px-4"
:style="{ marginTop: safeAreaInsets?.top + 'px' }"
>
<view class="mt-12">
<image src="/static/logo.svg" alt="" class="w-28 h-28 block mx-auto" />
</view>
<view class="text-center text-4xl main-title-color mt-4 test-unocss-apply">unibest</view>
<view class="text-center text-2xl mt-2 mb-8">最好用的 uniapp 开发模板</view>
<view class="text-justify max-w-100 m-auto text-4 indent mb-2">{{ description }}</view>
<view class="mt-8 text-center">
<text class="text-green-400">在线文档:</text>
<!-- #ifndef H5 -->
https://unibest.tech
<!-- #endif -->
<!-- #ifdef H5 -->
<a href="https://unibest.tech" target="_blank">https://unibest.tech</a>
<!-- #endif -->
</view>
</view>
</template>
<script lang="ts" setup>
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const author = ref('菲鸽')
const description = ref(
'unibest 是一个集成了多种工具和技术的 uniapp 开发模板,由 uniapp + Vue3 + Ts + Vite4 + UnoCss + UniUI + VSCode 构建,模板具有代码提示、自动格式化、统一配置、代码片段等功能,并内置了许多常用的基本组件和基本功能,让你编写 uniapp 拥有 best 体验。',
)
onLoad(() => {
console.log(author)
})
/** 激活“分享给好友” */
onShareAppMessage((options: Page.ShareAppMessageOption): Page.CustomShareContent => {
console.log('options:', options)
return {
title: 'unibest',
desc: 'unibest 演示示例',
path: '/pages/index/index?id=xxx',
}
})
</script>
<style>
.main-title-color {
color: #d14328;
}
.test-unocss-apply {
@apply m-4;
}
</style>
<route lang="json5">
{
layout: 'demo',
style: {
navigationBarTitleText: '请求',
},
}
</route>
<template>
<view class="mt-6">
<!-- http://localhost:9000/#/pages/index/request -->
<button @click="getFoo" class="my-4">测试 GET 请求</button>
<view class="text-xl">请求数据如下</view>
<view class="text-green h-10">{{ JSON.stringify(data) }}</view>
<button @click="postFoo" class="my-4">测试 POST 请求</button>
<view class="text-xl">请求数据如下</view>
<view class="text-green h-10">{{ JSON.stringify(data2) }}</view>
<view class="my-2">使用的是 laf 云后台</view>
<view class="text-green-400">我的推荐码,可以获得佣金</view>
<!-- #ifdef H5 -->
<view class="my-2 text-center">
<a class="my-2 text-center" :href="recommendUrl" target="_blank">{{ recommendUrl }}</a>
</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<view class="my-2 text-left text-sm">{{ recommendUrl }}</view>
<!-- #endif -->
</view>
</template>
<script lang="ts" setup>
import { getFooAPI, postFooAPI, IFooItem } from '@/service/foo'
const recommendUrl = ref('http://laf.run/signup?code=ohaOgIX')
onLoad(() => {
getFoo()
postFoo()
})
const data = ref<IFooItem>()
const getFoo = async () => {
const res = await getFooAPI('菲鸽')
data.value = res.data
}
const data2 = ref<IFooItem>()
const postFoo = async () => {
const res = await postFooAPI('菲鸽2')
data2.value = res.data
}
</script>
<route lang="json5" type="page">
{
style: { navigationBarTitleText: '登录' },
}
</route>
<template>
<view class="text-center">
<view class="leading-10">登录成功后会跳转回拦截前的页面</view>
<view class="p-10">
<uv-button type="primary" @click="login">登录</uv-button>
</view>
</view>
</template>
<script lang="ts" setup>
import { currRoute } from '@/utils'
import { useUserStore } from '@/store'
const userStore = useUserStore()
const login = () => {
userStore.setUserInfo({ nickname: '菲鸽', avatar: '', token: 'abcdef' })
const { query } = currRoute()
uni.redirectTo({ url: query.redirect })
}
onLoad((opt) => {
console.log('login onLoad', opt)
})
</script>
<style lang="scss" scoped>
//
</style>
<route lang="json5">
{
style: { navigationBarTitleText: '登录' },
}
</route>
<template>
<view class="p-4">
<view class="flex items-center leading-6" v-if="hasLogin">
<image class="w-8 h-8 rounded-full" :src="userStore.userInfo?.avatar"></image>
<view class="ml-2">{{ userStore.userInfo?.nickname }}</view>
</view>
<view class="flex items-center leading-6" v-else @click="show = true">
<view class="i-carbon-user-avatar"></view>
<view class="ml-2">点击显示微信头像</view>
</view>
<fly-login v-model="show" />
<fly-content :line="10" />
<button v-if="hasLogin" class="mt-2" @click="logout">退出登录</button>
</view>
</template>
<script lang="ts" setup name="WxLogin">
import { useUserStore } from '@/store'
const show = ref(false)
const userStore = useUserStore()
const hasLogin = computed(() => userStore.userInfo?.nickname)
const logout = () => {
uni.showModal({
title: '确认退出当前账号?',
success: (res) => {
if (res.confirm) {
userStore.clearUserInfo()
}
},
})
}
</script>
<route lang="json5">
{
style: { navigationBarTitleText: '我的' },
}
</route>
<template>
<view class="ml-4">wx的openid:</view>
<view class="ml-4">{{ openId }}</view>
<wx-login />
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store'
import { http } from '@/utils/http'
import WxLogin from './components/wx-login.vue'
const userStore = useUserStore()
const openId = ref('')
// 用户登录,获取openId
uni.login({
provider: 'weixin',
success: async ({ code }) => {
const res = await http<{ session_key: string; openid: string }>({
method: 'GET',
url: '/weixin/jscode2session',
data: {
code,
},
})
console.log('微信登录-1:', res)
// {code: 0, msg: "success", data: {session_key: "JTzhLVK+oM3X58uJ/heDcQ==", openid: "oSYa06xPVqjsK-eFYzt0kSPYu1q4"}}
openId.value = res.data.openid
userStore.setUserInfo({ openid: res.data.openid })
},
})
</script>
export interface IFooItem {
id: string
name: string
}
import { http, uniFileUpload } from '@/utils/http'
import type { IFooItem } from './foo.d'
export { IFooItem }
/** get 请求 */
export const getFooAPI = (name: string) => {
return http<IFooItem>({
url: `/foo`,
method: 'GET',
query: { name },
})
}
/** get 请求 */
export const postFooAPI = (name: string) => {
return http<IFooItem>({
url: `/foo`,
method: 'POST',
query: { name }, // post 请求也支持 query
data: { name },
})
}
// 文件上传
export const fileUpload = (data: IUniUploadFileOptions) => {
return uniFileUpload({
url: `/foo/upload`,
method: 'POST',
...data,
})
}
/** get 请求列表 */
export const getList = (page = 1, pageSize = 10) => {
return http<any>({
url: `/queryList`,
method: 'GET',
query: { page, pageSize },
})
}
import { http } from '@/utils/http'
import type { IFooItem } from './foo.d'
export { IFooItem }
/** get 请求 */
export const getMockAPI = (name: string) => {
return http<IFooItem>({
url: `/api/get`,
method: 'GET',
query: { name },
})
}
export {}
declare module 'vue' {
type Hooks = App.AppInstance & Page.PageInstance
interface ComponentCustomOptions extends Hooks {
$uv?: any
}
}
declare global {
interface Uni {
$uv?: any
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
<?xml version="1.0" encoding="UTF-8"?>
<svg id="_图层_2" data-name="图层 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 113.39 113.39">
<defs>
<style>
.cls-1 {
fill: none;
}
.cls-2 {
fill: #d14328;
}
.cls-3 {
fill: #2c8d3a;
}
</style>
</defs>
<g id="_图层_1-2" data-name="图层 1">
<g>
<rect class="cls-1" width="113.39" height="113.39"/>
<g>
<path class="cls-3" d="M86.31,11.34H25.08c-8.14,0-14.74,6.6-14.74,14.74v61.23c0,8.14,6.6,14.74,14.74,14.74h61.23c.12,0,.24-.02,.37-.02-9.76-.2-17.64-8.18-17.64-17.99,0-.56,.03-1.12,.08-1.67H34.1c-1.57,0-2.83-1.27-2.83-2.83V32.43c0-.78,.63-1.42,1.42-1.42h9.17c.78,0,1.42,.63,1.42,1.42v36.52c0,.78,.63,1.42,1.42,1.42h22.02c.78,0,1.42-.63,1.42-1.42V32.43c0-.78,.63-1.42,1.42-1.42h9.17c.78,0,1.42,.63,1.42,1.42v34.99c2.13-.89,4.47-1.39,6.92-1.39,5.66,0,10.7,2.63,14.01,6.72V26.08c0-8.14-6.6-14.74-14.74-14.74Z"/>
<g>
<path class="cls-2" d="M87.04,68.03c-8.83,0-16.01,7.18-16.01,16.01s7.18,16.01,16.01,16.01,16.01-7.18,16.01-16.01-7.18-16.01-16.01-16.01Zm-.27,24.84h-7.2v-3h1.18v-10.48h4.58v2.81h1.42c.84,0,1.46-.16,1.88-.48s.62-.87,.62-1.64c0-.69-.25-1.17-.74-1.45s-1.19-.42-2.09-.42h-6.84v-3h7.2c2.38,0,4.15,.38,5.31,1.15,1.16,.77,1.74,1.93,1.74,3.48,0,1.71-.83,2.93-2.5,3.64,1.07,.4,1.87,.95,2.39,1.65s.79,1.56,.79,2.58c0,3.44-2.58,5.16-7.73,5.16Z"/>
<path class="cls-2" d="M86.49,85.17h-1.16v4.7h1.8c.81,0,1.46-.18,1.94-.55s.72-.95,.72-1.73c0-.86-.25-1.48-.74-1.85s-1.35-.56-2.56-.56Z"/>
</g>
</g>
</g>
</g>
</svg>
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1712309809495" class="icon" viewBox="0 0 1049 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4978" xmlns:xlink="http://www.w3.org/1999/xlink" width="65.5625" height="64"><path d="M161.4336 0h624.1024c107.6224 0 161.4336 53.6832 161.4336 161.0752v687.7696c0 107.392-53.8112 161.0752-161.4336 161.0752H161.4336C53.8112 1009.92 0 956.2368 0 848.8448V161.0752C0 53.6832 53.8112 0 161.4336 0z" fill="#01B26A" p-id="4979"></path><path d="M672.1792 352.1024H181.632c-26.88 0-48.64-21.7088-48.64-48.512 0-26.8288 21.76-48.5376 48.64-48.5376h490.5472c26.88 0 48.64 21.7088 48.64 48.5376 0 26.8032-21.76 48.512-48.64 48.512zM485.888 627.84H181.8624c-26.88 0-48.64-21.7344-48.64-48.5376s21.76-48.5376 48.64-48.5376H485.888c26.88 0 48.64 21.76 48.64 48.5376 0 26.8032-21.76 48.5376-48.64 48.5376z" fill="#FFFFFF" p-id="4980"></path><path d="M523.264 761.4208C523.264 906.4448 641.1264 1024 786.432 1024 931.7888 1024 1049.6 906.4448 1049.6 761.4208c0-144.9984-117.8112-262.5536-263.168-262.5536-145.3312 0-263.168 117.5552-263.168 262.5536z" fill="#28D493" fill-opacity=".517" p-id="4981"></path><path d="M786.432 498.944c-128.768-0.1792-238.72 92.6976-259.84 219.4432a262.4512 262.4512 0 0 0 174.72 291.5328h84.0448c89.088 0.1024 161.4336-71.8592 161.6128-160.768V553.5232a261.8368 261.8368 0 0 0-160.512-54.6048z" fill="#00AA69" p-id="4982"></path><path d="M724.0448 918.272a48.64 48.64 0 0 1-44.0832-28.1088 48.4352 48.4352 0 0 1 6.9376-51.7376l71.1936-84.0192v-115.8144c0-26.8032 21.7856-48.5376 48.64-48.5376 26.88 0 48.64 21.7344 48.64 48.5376v133.4528c0 11.4688-4.0704 22.5536-11.4688 31.3088l-82.688 97.6128c-9.216 10.9312-22.8352 17.28-37.1712 17.28z" fill="#FFFFFF" p-id="4983"></path></svg>
\ No newline at end of file \ No newline at end of file
// src/store/useCountStore.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCountStore = defineStore(
'count',
() => {
const count = ref(0)
const increment = () => {
count.value++
}
const decrement = () => {
count.value--
}
const reset = () => {
count.value = 0
}
return {
count,
decrement,
increment,
reset,
}
},
{
persist: true,
},
)
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate' // 数据持久化
const store = createPinia()
store.use(
createPersistedState({
storage: {
getItem: uni.getStorageSync,
setItem: uni.setStorageSync,
},
}),
)
export default store
// 模块统一导出
export * from './user'
export * from './count'
import { defineStore } from 'pinia'
import { ref } from 'vue'
const initState = { nickname: '', avatar: '' }
export const useUserStore = defineStore(
'user',
() => {
const userInfo = ref<IUserInfo>({ ...initState })
const setUserInfo = (val: IUserInfo) => {
userInfo.value = val
}
const clearUserInfo = () => {
userInfo.value = { ...initState }
}
const reset = () => {
userInfo.value = { ...initState }
}
const isLogined = computed(() => !!userInfo.value.token)
return {
userInfo,
setUserInfo,
clearUserInfo,
isLogined,
reset,
}
},
{
persist: true,
},
)
/* https://www.iconfont.cn/manage/index?manage_type=myprojects&projectId=4543091 */
@font-face {
font-family: iconfont; /* Project id 4543091 */
src:
url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAOwAAsAAAAAB9AAAANjAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDHAqDBIJqATYCJAMQCwoABCAFhGcHPRvnBsgusG3kMyE15/44PsBX09waBHv0REDt97oHAQDFrOIyPirRiULQ+TJcXV0hCYTuVFcBC915/2vX/32Q80hkZ5PZGZ9snvwruVLloidKqYN6iKC53bOtbKwVLSIi3W6zCWZbs3VbER3j9JpGX3ySYcc94IQRTK5s4epS/jSqIgvg37qlY2/jwQN7D9ADpfRCmIknQByTscVZPTBr+hnnCKg2o4bjakvXEPjuY65DJGeJNtBUhn1JxOBuB2UZmUpBOXdsFp4oxOv4GHgs3h/+wRDcicqSZJG1q9kK1z/Af9NpqxjpC2QaAdpHlCFh4spcYXs5sMWpSk5wUj31G2dLQKVKkZ/w7f/8/i/A3JVUSZK9f7xIKJeU14IFpBI/Qfkkz46GT/CuaGREfCtKJUougWeQWHvVC5Lcz2BGS+SePR99vj3yjJx7h574tp7uWcOh4yfaTjS/245TT/vkQrN+a7RLkK8+Vd+bz+FSGh+9srDQKPeJ2s29z7ah4+efdoxefRbbGwfy7ht+SuIWukzsu1b6ePP+6kN1aamb47qsPim1Ia3xdEpDcl1dckPKGYnneI23+57r2W1Mmkqs6ajrChRCs5qyQ66rTVWhgZaG7toOeHm5cxn0sSQuNDEgcUTdNTSupKI1JRZih/JssAUKezPeOJJzbNozF6zWJuuVavVU5Tgtkop/SDzHa7ytvnCTq0PhkEfi4xLLtb0PuwyOAYqmrYQApFJyoJjTnfz+ve94vvv2f/yWgxl8Jd8Di2DRDPuob59mU/+VfDCROQyR8xSnmP9fXm7liagmN39OlmbvjqG0sMsJKrU0EFXogaRSH5bNY1CmxhyUq7QC1cY1T67RwuQk5CoM2RUQNLoEUb03kDS6h2XzcyjT7iOUa/QXqq1Hn6/GUBAaGcGcWJFlGUmCoVOp8kLvABHnVczGYiOE2SVEUH5OXj/TSnTCDjHAviAWcE4RZYaGWszNiKoayGSGTASeY+PcrMjNpVMvyREMDRoxBMYRVojFMkQiMOhohubdzxtAiOapMMbERpKMnQT9SL4ceQysVdJZVa9kEbsFogIcRyEUE2kN0mL7CDVIGhBzupWMEHA5bDvipgq5hKJcKef8ivbx1kC15KgcYkghhzLxYNntxoKCReJ82jAHAAA=')
format('woff2'),
url('//at.alicdn.com/t/c/font_4543091_njpo5b95nl.woff?t=1715485842402') format('woff'),
url('//at.alicdn.com/t/c/font_4543091_njpo5b95nl.ttf?t=1715485842402') format('truetype');
}
.iconfont {
font-family: iconfont !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-my::before {
content: '\e78c';
}
.icon-package::before {
content: '\e9c2';
}
.icon-chat::before {
content: '\e600';
}
@import './iconfont.css';
.test {
// 可以通过 @apply 多个样式封装整体样式
@apply mt-4 ml-4;
padding-top: 4px;
color: red;
}
.icon {
width: 1em;
height: 1em;
overflow: hidden;
vertical-align: -0.15em;
fill: currentcolor;
}
// 全局字体引用 DEMO
// @font-face {
// font-family: TiTi;
// src: url('./fonts/PangMenZhengDaoBiaoTiTi-1.ttf');
// }
// .titi {
// font-family: TiTi, Arial, sans-serif;
// }
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
export {}
declare global {
const EffectScope: typeof import('vue')['EffectScope']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const effectScope: typeof import('vue')['effectScope']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const markRaw: typeof import('vue')['markRaw']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onAddToFavorites: typeof import('@dcloudio/uni-app')['onAddToFavorites']
const onBackPress: typeof import('@dcloudio/uni-app')['onBackPress']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onError: typeof import('@dcloudio/uni-app')['onError']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onHide: typeof import('@dcloudio/uni-app')['onHide']
const onLaunch: typeof import('@dcloudio/uni-app')['onLaunch']
const onLoad: typeof import('@dcloudio/uni-app')['onLoad']
const onMounted: typeof import('vue')['onMounted']
const onNavigationBarButtonTap: typeof import('@dcloudio/uni-app')['onNavigationBarButtonTap']
const onNavigationBarSearchInputChanged: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputChanged']
const onNavigationBarSearchInputClicked: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputClicked']
const onNavigationBarSearchInputConfirmed: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputConfirmed']
const onNavigationBarSearchInputFocusChanged: typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputFocusChanged']
const onPageNotFound: typeof import('@dcloudio/uni-app')['onPageNotFound']
const onPageScroll: typeof import('@dcloudio/uni-app')['onPageScroll']
const onPullDownRefresh: typeof import('@dcloudio/uni-app')['onPullDownRefresh']
const onReachBottom: typeof import('@dcloudio/uni-app')['onReachBottom']
const onReady: typeof import('@dcloudio/uni-app')['onReady']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onResize: typeof import('@dcloudio/uni-app')['onResize']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onShareAppMessage: typeof import('@dcloudio/uni-app')['onShareAppMessage']
const onShareTimeline: typeof import('@dcloudio/uni-app')['onShareTimeline']
const onShow: typeof import('@dcloudio/uni-app')['onShow']
const onTabItemTap: typeof import('@dcloudio/uni-app')['onTabItemTap']
const onThemeChange: typeof import('@dcloudio/uni-app')['onThemeChange']
const onUnhandledRejection: typeof import('@dcloudio/uni-app')['onUnhandledRejection']
const onUnload: typeof import('@dcloudio/uni-app')['onUnload']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
const provide: typeof import('vue')['provide']
const reactive: typeof import('vue')['reactive']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useEcharts: typeof import('../hooks/useEcharts')['useEcharts']
const useId: typeof import('vue')['useId']
const useModel: typeof import('vue')['useModel']
const useNavbarWeixin: typeof import('../hooks/useNavbarWeixin')['default']
const useRequest: typeof import('../hooks/useRequest')['default']
const useSlots: typeof import('vue')['useSlots']
const useTemplateRef: typeof import('vue')['useTemplateRef']
const useUpload: typeof import('../hooks/useUpload')['default']
const useUpload2: typeof import('../hooks/useUpload2')['default']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue')
}
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface GlobalComponents {}
interface ComponentCustomProperties {
readonly EffectScope: UnwrapRef<typeof import('vue')['EffectScope']>
readonly computed: UnwrapRef<typeof import('vue')['computed']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
readonly defineAsyncComponent: UnwrapRef<typeof import('vue')['defineAsyncComponent']>
readonly defineComponent: UnwrapRef<typeof import('vue')['defineComponent']>
readonly effectScope: UnwrapRef<typeof import('vue')['effectScope']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly h: UnwrapRef<typeof import('vue')['h']>
readonly inject: UnwrapRef<typeof import('vue')['inject']>
readonly isProxy: UnwrapRef<typeof import('vue')['isProxy']>
readonly isReactive: UnwrapRef<typeof import('vue')['isReactive']>
readonly isReadonly: UnwrapRef<typeof import('vue')['isReadonly']>
readonly isRef: UnwrapRef<typeof import('vue')['isRef']>
readonly markRaw: UnwrapRef<typeof import('vue')['markRaw']>
readonly nextTick: UnwrapRef<typeof import('vue')['nextTick']>
readonly onActivated: UnwrapRef<typeof import('vue')['onActivated']>
readonly onAddToFavorites: UnwrapRef<typeof import('@dcloudio/uni-app')['onAddToFavorites']>
readonly onBackPress: UnwrapRef<typeof import('@dcloudio/uni-app')['onBackPress']>
readonly onBeforeMount: UnwrapRef<typeof import('vue')['onBeforeMount']>
readonly onBeforeUnmount: UnwrapRef<typeof import('vue')['onBeforeUnmount']>
readonly onBeforeUpdate: UnwrapRef<typeof import('vue')['onBeforeUpdate']>
readonly onDeactivated: UnwrapRef<typeof import('vue')['onDeactivated']>
readonly onError: UnwrapRef<typeof import('@dcloudio/uni-app')['onError']>
readonly onErrorCaptured: UnwrapRef<typeof import('vue')['onErrorCaptured']>
readonly onHide: UnwrapRef<typeof import('@dcloudio/uni-app')['onHide']>
readonly onLaunch: UnwrapRef<typeof import('@dcloudio/uni-app')['onLaunch']>
readonly onLoad: UnwrapRef<typeof import('@dcloudio/uni-app')['onLoad']>
readonly onMounted: UnwrapRef<typeof import('vue')['onMounted']>
readonly onNavigationBarButtonTap: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarButtonTap']>
readonly onNavigationBarSearchInputChanged: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputChanged']>
readonly onNavigationBarSearchInputClicked: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputClicked']>
readonly onNavigationBarSearchInputConfirmed: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputConfirmed']>
readonly onNavigationBarSearchInputFocusChanged: UnwrapRef<typeof import('@dcloudio/uni-app')['onNavigationBarSearchInputFocusChanged']>
readonly onPageNotFound: UnwrapRef<typeof import('@dcloudio/uni-app')['onPageNotFound']>
readonly onPageScroll: UnwrapRef<typeof import('@dcloudio/uni-app')['onPageScroll']>
readonly onPullDownRefresh: UnwrapRef<typeof import('@dcloudio/uni-app')['onPullDownRefresh']>
readonly onReachBottom: UnwrapRef<typeof import('@dcloudio/uni-app')['onReachBottom']>
readonly onReady: UnwrapRef<typeof import('@dcloudio/uni-app')['onReady']>
readonly onRenderTracked: UnwrapRef<typeof import('vue')['onRenderTracked']>
readonly onRenderTriggered: UnwrapRef<typeof import('vue')['onRenderTriggered']>
readonly onResize: UnwrapRef<typeof import('@dcloudio/uni-app')['onResize']>
readonly onScopeDispose: UnwrapRef<typeof import('vue')['onScopeDispose']>
readonly onServerPrefetch: UnwrapRef<typeof import('vue')['onServerPrefetch']>
readonly onShareAppMessage: UnwrapRef<typeof import('@dcloudio/uni-app')['onShareAppMessage']>
readonly onShareTimeline: UnwrapRef<typeof import('@dcloudio/uni-app')['onShareTimeline']>
readonly onShow: UnwrapRef<typeof import('@dcloudio/uni-app')['onShow']>
readonly onTabItemTap: UnwrapRef<typeof import('@dcloudio/uni-app')['onTabItemTap']>
readonly onThemeChange: UnwrapRef<typeof import('@dcloudio/uni-app')['onThemeChange']>
readonly onUnhandledRejection: UnwrapRef<typeof import('@dcloudio/uni-app')['onUnhandledRejection']>
readonly onUnload: UnwrapRef<typeof import('@dcloudio/uni-app')['onUnload']>
readonly onUnmounted: UnwrapRef<typeof import('vue')['onUnmounted']>
readonly onUpdated: UnwrapRef<typeof import('vue')['onUpdated']>
readonly onWatcherCleanup: UnwrapRef<typeof import('vue')['onWatcherCleanup']>
readonly provide: UnwrapRef<typeof import('vue')['provide']>
readonly reactive: UnwrapRef<typeof import('vue')['reactive']>
readonly readonly: UnwrapRef<typeof import('vue')['readonly']>
readonly ref: UnwrapRef<typeof import('vue')['ref']>
readonly resolveComponent: UnwrapRef<typeof import('vue')['resolveComponent']>
readonly shallowReactive: UnwrapRef<typeof import('vue')['shallowReactive']>
readonly shallowReadonly: UnwrapRef<typeof import('vue')['shallowReadonly']>
readonly shallowRef: UnwrapRef<typeof import('vue')['shallowRef']>
readonly toRaw: UnwrapRef<typeof import('vue')['toRaw']>
readonly toRef: UnwrapRef<typeof import('vue')['toRef']>
readonly toRefs: UnwrapRef<typeof import('vue')['toRefs']>
readonly toValue: UnwrapRef<typeof import('vue')['toValue']>
readonly triggerRef: UnwrapRef<typeof import('vue')['triggerRef']>
readonly unref: UnwrapRef<typeof import('vue')['unref']>
readonly useAttrs: UnwrapRef<typeof import('vue')['useAttrs']>
readonly useCssModule: UnwrapRef<typeof import('vue')['useCssModule']>
readonly useCssVars: UnwrapRef<typeof import('vue')['useCssVars']>
readonly useEcharts: UnwrapRef<typeof import('../hooks/useEcharts')['useEcharts']>
readonly useId: UnwrapRef<typeof import('vue')['useId']>
readonly useModel: UnwrapRef<typeof import('vue')['useModel']>
readonly useNavbarWeixin: UnwrapRef<typeof import('../hooks/useNavbarWeixin')['default']>
readonly useRequest: UnwrapRef<typeof import('../hooks/useRequest')['default']>
readonly useSlots: UnwrapRef<typeof import('vue')['useSlots']>
readonly useTemplateRef: UnwrapRef<typeof import('vue')['useTemplateRef']>
readonly useUpload: UnwrapRef<typeof import('../hooks/useUpload')['default']>
readonly watch: UnwrapRef<typeof import('vue')['watch']>
readonly watchEffect: UnwrapRef<typeof import('vue')['watchEffect']>
readonly watchPostEffect: UnwrapRef<typeof import('vue')['watchPostEffect']>
readonly watchSyncEffect: UnwrapRef<typeof import('vue')['watchSyncEffect']>
}
}
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by vite-plugin-uni-components
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {
export interface GlobalComponents {
AppTest: typeof import('./../components/AppTest.vue')['default']
AppTest2: typeof import('./../components/app-test-dir/AppTest2.vue')['default']
FlyContent: typeof import('./../components/fly-content/fly-content.vue')['default']
FlyHeader: typeof import('./../components/fly-header/fly-header.vue')['default']
FlyLogin: typeof import('./../components/fly-login/fly-login.vue')['default']
FlyNavbar: typeof import('./../components/fly-navbar/fly-navbar.vue')['default']
Loading1: typeof import('./../components/qiun-loading/loading1.vue')['default']
Loading2: typeof import('./../components/qiun-loading/loading2.vue')['default']
Loading3: typeof import('./../components/qiun-loading/loading3.vue')['default']
Loading4: typeof import('./../components/qiun-loading/loading4.vue')['default']
Loading5: typeof import('./../components/qiun-loading/loading5.vue')['default']
QiunDataCharts: typeof import('./../components/qiun-data-charts/qiun-data-charts.vue')['default']
QiunError: typeof import('./../components/qiun-error/qiun-error.vue')['default']
QiunLoading: typeof import('./../components/qiun-loading/qiun-loading.vue')['default']
QiunTitleBar: typeof import('./../components/qiun-title-bar/qiun-title-bar.vue')['default']
SvgIcon: typeof import('./../components/SvgIcon.vue')['default']
}
}
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by vite-plugin-uni-pages
interface NavigateToOptions {
url: "/pages/index/index" |
"/pages/demo/index" |
"/pages/index/request" |
"/pages/login/index" |
"/pages/my/index" |
"/pages/demo/base/auto-import" |
"/pages/demo/base/css" |
"/pages/demo/base/enum" |
"/pages/demo/base/env" |
"/pages/demo/base/iconfont" |
"/pages/demo/base/mock" |
"/pages/demo/base/mp-weixin-share" |
"/pages/demo/base/navbar" |
"/pages/demo/base/no-navbar" |
"/pages/demo/base/pinia" |
"/pages/demo/base/request" |
"/pages/demo/base/request2" |
"/pages/demo/base/route-interceptor" |
"/pages/demo/base/svg" |
"/pages/demo/base/throughout" |
"/pages/demo/base/uni-ui-icons" |
"/pages/demo/base/uni-ui" |
"/pages/demo/base/unocss-icons" |
"/pages/demo/base/unocss" |
"/pages/demo/base/upload" |
"/pages/demo/base/upload2" |
"/pages/demo/base/uv-ui" |
"/pages/demo/base/vconsole" |
"/pages/demo/base/wot" |
"/pages/demo/page/clock" |
"/pages/demo/page/clock2" |
"/pages/demo/page/floating-bubble" |
"/pages/demo/page/i18n" |
"/pages/demo/page/sign" |
"/pages/demo/page/waterfall" |
"/pages/demo/route-interceptor/index" |
"/pages/demo/route-interceptor/login-auto" |
"/pages/demo/route-interceptor/login-model" |
"/pages/demo/route-interceptor/login-page" |
"/pages/demo/page/echarts/index" |
"/pages/demo/page/img-min/index" |
"/pages/demo/page/lottery/big-wheel" |
"/pages/demo/page/lottery/nine-grid" |
"/pages/demo/page/sp-editor/index" |
"/pages/demo/page/ucharts/index" |
"/pages/demo/page/z-paging/index" |
"/pages-sub/demo/index";
}
interface RedirectToOptions extends NavigateToOptions {}
interface SwitchTabOptions {
url: "/pages/index/index" | "/pages/demo/index"
}
type ReLaunchOptions = NavigateToOptions | SwitchTabOptions;
declare interface Uni {
navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void;
redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void;
switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void;
reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void;
}
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
// 全局要用的类型放到这里
type IResData<T> = {
code: number
msg: string
data: T
}
// uni.uploadFile文件上传参数
type IUniUploadFileOptions = {
file?: File
files?: UniApp.UploadFileOptionFiles[]
filePath?: string
name?: string
formData?: any
}
type IUserInfo = {
nickname?: string
avatar?: string
/** 微信的 openid,非微信没有这个字段 */
openid?: string
token?: string
}
enum TestEnum {
A = 'a',
B = 'b',
}
declare type Recordable<T = any> = Record<string, T>
/* stylelint-disable comment-empty-line-before */
/**
* 这里是uni-app内置的常用样式变量
*
* uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量
* 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App
*
*/
/**
* 如果你是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: #fff;
$uni-bg-color-grey: #f8f8f8;
$uni-bg-color-hover: #f1f1f1; // 点击状态颜色
$uni-bg-color-mask: rgb(0 0 0 / 40%); // 遮罩颜色
/* 边框颜色 */
$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: #555; // 二级标题颜色
$uni-font-size-subtitle: 18px;
$uni-color-paragraph: #3f536e; // 文章段落颜色
$uni-font-size-paragraph: 15px;
## 0.9.8(2024-12-20)
- fix: 修复 APP 无法放大问题
## 0.9.7(2024-12-02)
- feat: uniapp 增加`landscape`,当`landscape`为`true`时旋转90deg达到横屏效果。
- feat: 支持uniapp x 微信小程序
## 0.9.6(2024-07-23)
- fix: 修复 uni is not defined
## 0.9.5(2024-07-19)
- chore: 鸿蒙`measureText`为异步,异步字体不正常,使用模拟方式。
## 0.9.4(2024-07-18)
- chore: 更新文档
## 0.9.3(2024-07-16)
- feat: 鸿蒙 canvas 事件缺失,待官方修复,如何在鸿蒙使用请看文档`常见问题 vue3`
## 0.9.2(2024-07-12)
- chore: 删除多余文件
## 0.9.1(2024-07-12)
- fix: 修复 安卓5不显示图表问题
## 0.9.0(2024-06-13)
- chore: 合并nvue和uvue
## 0.8.9(2024-05-19)
- chore: 更新文档
## 0.8.8(2024-05-13)
- chore: 更新文档和uvue示例
## 0.8.7(2024-04-26)
- fix: uniapp x需要HBX 4.13以上
## 0.8.6(2024-04-10)
- feat: 支持 uniapp x ios
## 0.8.5(2024-04-03)
- fix: 修复 nvue `reset`传值不生效问题
- feat: 支持 uniapp x web
## 0.8.4(2024-01-27)
- chore: 更新文档
## 0.8.3(2024-01-21)
- chore: 更新文档
## 0.8.2(2024-01-21)
- feat: 支持 `uvue`
## 0.8.1(2023-08-24)
- fix: app 的`touch`事件为`object` 导致无法显示 `tooltip`
## 0.8.0(2023-08-22)
- fix: 离屏 报错问题
- fix: 微信小程序PC无法使用事件
- chore: 更新文档
## 0.7.9(2023-07-29)
- chore: 更新文档
## 0.7.8(2023-07-29)
- fix: 离屏 报错问题
## 0.7.7(2023-07-27)
- chore: 更新文档
- chore: lime-echart 里的示例使用自定tooltips
- feat: 对支持离屏的使用离屏创建(微信、字节、支付宝)
## 0.7.6(2023-06-30)
- fix: vue3 报`width`的错
## 0.7.5(2023-05-25)
- chore: 更新文档 和 demo, 使用`lime-echart`这个标签即可查看示例
## 0.7.4(2023-05-22)
- chore: 增加关于钉钉小程序上传时提示安全问题的说明及修改建议
## 0.7.3(2023-05-16)
- chore: 更新 vue3 非微信小程序平台可能缺少`wx`的说明
## 0.7.2(2023-05-16)
- chore: 更新 vue3 非微信小程序平台的可以缺少`wx`的说明
## 0.7.1(2023-04-26)
- chore: 更新demo,使用`lime-echart`这个标签即可查看示例
- chore:微信小程序的`tooltip`文字有阴影,怀疑是微信的锅,临时解决方法是`tooltip.shadowBlur = 0`
## 0.7.0(2023-04-24)
- fix: 修复`setAttribute is not a function`
## 0.6.9(2023-04-15)
- chore: 更新文档,vue3请使用echarts esm的包
## 0.6.8(2023-03-22)
- feat: mac pc无法使用canvas 2d
## 0.6.7(2023-03-17)
- feat: 更新文档
## 0.6.6(2023-03-17)
- feat: 微信小程序PC已经支持canvas 2d,故去掉判断PC
## 0.6.5(2022-11-03)
- fix: 某些手机touches为对象,导致无法交互。
## 0.6.4(2022-10-28)
- fix: 优化点击事件的触发条件
## 0.6.3(2022-10-26)
- fix: 修复 dataZoom 拖动问题
## 0.6.2(2022-10-23)
- fix: 修复 飞书小程序 尺寸问题
## 0.6.1(2022-10-19)
- fix: 修复 PC mousewheel 事件 鼠标位置不准确的BUG,不兼容火狐!
- feat: showLoading 增加传参
## 0.6.0(2022-09-16)
- feat: 增加PC的mousewheel事件
## 0.5.4(2022-09-16)
- fix: 修复 nvue 动态数据不显示问题
## 0.5.3(2022-09-16)
- feat: 增加enableHover属性, 在PC端时当鼠标进入显示tooltip,不必按下。
- chore: 更新文档
## 0.5.2(2022-09-16)
- feat: 增加enableHover属性, 在PC端时当鼠标进入显示tooltip,不必按下。
## 0.5.1(2022-09-16)
- fix: 修复nvue报错
## 0.5.0(2022-09-15)
- feat: init(echarts, theme?:string, opts?:{}, callback: function(chart))
## 0.4.8(2022-09-11)
- feat: 增加 @finished
## 0.4.7(2022-08-24)
- chore: 去掉 stylus
## 0.4.6(2022-08-24)
- feat: 增加 beforeDelay
## 0.4.5(2022-08-12)
- chore: 更新文档
## 0.4.4(2022-08-12)
- fix: 修复 resize 无参数时报错
## 0.4.3(2022-08-07)
# 评论有说本插件对新手不友好,让我做不好就不要发出来。 还有的说跟官网一样,发出来做什么,给我整无语了。
# 所以在此提醒一下准备要下载的你,如果你从未使用过 echarts 请不要下载 或 谨慎下载。
# 如果你确认要下载,麻烦看完文档。还有请注意插件是让echarts在uniapp能运行,API 配置请自行去官网查阅!
# 如果你不会echarts 但又需要图表,市场上有个很优秀的图表插件 uchart 你可以去使用这款插件,uchart的作者人很好,也热情。
# 每个人都有自己的本职工作,如果你能力强可以自行兼容,如果使用了他人的插件也麻烦尊重他人的成果和劳动时间。谢谢。
# 为了心情愉悦,本人已经使用插件屏蔽差评。
- chore: 更新文档
## 0.4.2(2022-07-20)
- feat: 增加 resize
## 0.4.1(2022-06-07)
- fix: 修复 canvasToTempFilePath 不生效问题
## 0.4.0(2022-06-04)
- chore 为了词云 增加一个canvas 标签
- 词云下载地址[echart-wordcloud](https://ext.dcloud.net.cn/plugin?id=8430)
## 0.3.9(2022-06-02)
- chore: 更新文档
- tips: lines 不支持 `trailLength`
## 0.3.8(2022-05-31)
- fix: 修复 因mouse事件冲突tooltip跳动问题
## 0.3.7(2022-05-26)
- chore: 更新文档
- chore: 设置默认宽高300px
- fix: 修复 vue3 微信小程序 拖影BUG
- chore: 支持PC
## 0.3.5(2022-04-28)
- chore: 更新使用方式
- 🔔 必须使用hbuilderx 3.4.8-alpha以上
## 0.3.4(2021-08-03)
- chore: 增加 setOption的参数值
## 0.3.3(2021-07-22)
- fix: 修复 径向渐变报错的问题
## 0.3.2(2021-07-09)
- chore: 统一命名规范,无须主动引入组件
## [代码示例站点1](https://limeui.qcoon.cn/#/echart-example)
## [代码示例站点2](http://liangei.gitee.io/limeui/#/echart-example)
## 0.3.1(2021-06-21)
- fix: 修复 app-nvue ios is-enable 无效的问题
## [代码示例站点1](https://limeui.qcoon.cn/#/echart-example)
## [代码示例站点2](http://liangei.gitee.io/limeui/#/echart-example)
## 0.3.0(2021-06-14)
- fix: 修复 头条系小程序 2d 报 JSON.stringify 的问题
- 目前 头条系小程序 2d 无法在开发工具上预览,划动图表页面无法滚动,axisLabel 字体颜色无法更改,建议使用非2d。
## 0.2.9(2021-06-06)
- fix: 修复 头条系小程序 2d 放大的BUG
- 头条系小程序 2d 无法在开发工具上预览,也存在划动图表页面无法滚动的问题。
## [代码示例:http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.8(2021-05-19)
- fix: 修复 微信小程序 PC 显示过大的问题
## 0.2.7(2021-05-19)
- fix: 修复 微信小程序 PC 不显示问题
## [代码示例:http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.6(2021-05-14)
- feat: 支持 `image`
- feat: props 增加 `ec.clear`,更新时是否先删除图表样式
- feat: props 增加 `isDisableScroll` ,触摸图表时是否禁止页面滚动
- feat: props 增加 `webviewStyles` ,webview 的样式, 仅nvue有效
## 0.2.5(2021-05-13)
- docs: 插件用到了css 预编译器 [stylus](https://ext.dcloud.net.cn/plugin?name=compile-stylus) 请安装它
## 0.2.4(2021-05-12)
- fix: 修复 百度平台 多个图表ctx 和 渐变色 bug
- ## [代码示例:http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.3(2021-05-10)
- feat: 增加 `canvasToTempFilePath` 方法,用于生成图片
```js
this.$refs.chart.canvasToTempFilePath({success: (res) => {
console.log('tempFilePath:', res.tempFilePath)
}})
```
## 0.2.2(2021-05-10)
- feat: 增加 `dispose` 方法,用于销毁实例
- feat: 增加 `isClickable` 是否派发点击
- feat: 实验性的支持 `nvue` 使用要慎重考虑
- ## [代码示例:http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.2.1(2021-05-06)
- fix:修复 微信小程序 json 报错
- chore: `reset` 更改为 `setChart`
- feat: 增加 `isEnable` 开启初始化 启用这个后 无须再使用`init`方法
```html
<l-echart ref="chart" is-enable />
```
```js
// 显示加载
this.$refs.chart.showLoading()
// 使用实例回调
this.$refs.chart.setChart(chart => ...code)
// 直接设置图表配置
this.$refs.chart.setOption(data)
```
## 0.2.0(2021-05-05)
- fix:修复 头条 百度 偏移的问题
- docs: 更新文档
## [代码示例:http://liangei.gitee.io/limeui/#/echart-example](http://liangei.gitee.io/limeui/#/echart-example)
## 0.1.0(2021-05-02)
- chore: 第一次上传,基本全端兼容,使用方法与官网一致。
- 已知BUG:非2d 无法使用背景色,已反馈官方
- 已知BUG:头条 百度 有许些偏移
- 后期计划:兼容nvue
import {getDeviceInfo} from './utils';
const cacheChart = {}
const fontSizeReg = /([\d\.]+)px/;
class EventEmit {
constructor() {
this.__events = {};
}
on(type, listener) {
if (!type || !listener) {
return;
}
const events = this.__events[type] || [];
events.push(listener);
this.__events[type] = events;
}
emit(type, e) {
if (type.constructor === Object) {
e = type;
type = e && e.type;
}
if (!type) {
return;
}
const events = this.__events[type];
if (!events || !events.length) {
return;
}
events.forEach((listener) => {
listener.call(this, e);
});
}
off(type, listener) {
const __events = this.__events;
const events = __events[type];
if (!events || !events.length) {
return;
}
if (!listener) {
delete __events[type];
return;
}
for (let i = 0, len = events.length; i < len; i++) {
if (events[i] === listener) {
events.splice(i, 1);
i--;
}
}
}
}
class Image {
constructor() {
this.currentSrc = null
this.naturalHeight = 0
this.naturalWidth = 0
this.width = 0
this.height = 0
this.tagName = 'IMG'
}
set src(src) {
this.currentSrc = src
uni.getImageInfo({
src,
success: (res) => {
this.naturalWidth = this.width = res.width
this.naturalHeight = this.height = res.height
this.onload()
},
fail: () => {
this.onerror()
}
})
}
get src() {
return this.currentSrc
}
}
class OffscreenCanvas {
constructor(ctx, com, canvasId) {
this.tagName = 'canvas'
this.com = com
this.canvasId = canvasId
this.ctx = ctx
}
set width(w) {
this.com.offscreenWidth = w
}
set height(h) {
this.com.offscreenHeight = h
}
get width() {
return this.com.offscreenWidth || 0
}
get height() {
return this.com.offscreenHeight || 0
}
getContext(type) {
return this.ctx
}
getImageData() {
return new Promise((resolve, reject) => {
this.com.$nextTick(() => {
uni.canvasGetImageData({
x:0,
y:0,
width: this.com.offscreenWidth,
height: this.com.offscreenHeight,
canvasId: this.canvasId,
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err)
},
}, this.com)
})
})
}
}
export class Canvas {
constructor(ctx, com, isNew, canvasNode={}) {
cacheChart[com.canvasId] = {ctx}
this.canvasId = com.canvasId;
this.chart = null;
this.isNew = isNew
this.tagName = 'canvas'
this.canvasNode = canvasNode;
this.com = com;
if (!isNew) {
this._initStyle(ctx)
}
this._initEvent();
this._ee = new EventEmit()
}
getContext(type) {
if (type === '2d') {
return this.ctx;
}
}
setAttribute(key, value) {
if(key === 'aria-label') {
this.com['ariaLabel'] = value
}
}
setChart(chart) {
this.chart = chart;
}
createOffscreenCanvas(param){
if(!this.children) {
this.com.isOffscreenCanvas = true
this.com.offscreenWidth = param.width||300
this.com.offscreenHeight = param.height||300
const com = this.com
const canvasId = this.com.offscreenCanvasId
const context = uni.createCanvasContext(canvasId, this.com)
this._initStyle(context)
this.children = new OffscreenCanvas(context, com, canvasId)
}
return this.children
}
appendChild(child) {
console.log('child', child)
}
dispatchEvent(type, e) {
if(typeof type == 'object') {
this._ee.emit(type.type, type);
} else {
this._ee.emit(type, e);
}
return true
}
attachEvent() {
}
detachEvent() {
}
addEventListener(type, listener) {
this._ee.on(type, listener)
}
removeEventListener(type, listener) {
this._ee.off(type, listener)
}
_initCanvas(zrender, ctx) {
// zrender.util.getContext = function() {
// return ctx;
// };
// zrender.util.$override('measureText', function(text, font) {
// ctx.font = font || '12px sans-serif';
// return ctx.measureText(text, font);
// });
}
_initStyle(ctx, child) {
const styles = [
'fillStyle',
'strokeStyle',
'fontSize',
'globalAlpha',
'opacity',
'textAlign',
'textBaseline',
'shadow',
'lineWidth',
'lineCap',
'lineJoin',
'lineDash',
'miterLimit',
// #ifdef H5
'font',
// #endif
];
const colorReg = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/g;
styles.forEach(style => {
Object.defineProperty(ctx, style, {
set: value => {
// #ifdef H5
if (style === 'font' && fontSizeReg.test(value)) {
const match = fontSizeReg.exec(value);
ctx.setFontSize(match[1]);
return;
}
// #endif
if (style === 'opacity') {
ctx.setGlobalAlpha(value)
return;
}
if (style !== 'fillStyle' && style !== 'strokeStyle' || value !== 'none' && value !== null) {
// #ifdef H5 || APP-PLUS || MP-BAIDU
if(typeof value == 'object') {
if (value.hasOwnProperty('colorStop') || value.hasOwnProperty('colors')) {
ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
}
return
}
// #endif
// #ifdef MP-TOUTIAO
if(colorReg.test(value)) {
value = value.replace(colorReg, '#$1$1$2$2$3$3')
}
// #endif
ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
}
}
});
});
if(!this.isNew && !child) {
ctx.uniDrawImage = ctx.drawImage
ctx.drawImage = (...a) => {
a[0] = a[0].src
ctx.uniDrawImage(...a)
}
}
if(!ctx.createRadialGradient) {
ctx.createRadialGradient = function() {
return ctx.createCircularGradient(...[...arguments].slice(-3))
};
}
// 字节不支持
if (!ctx.strokeText) {
ctx.strokeText = (...a) => {
ctx.fillText(...a)
}
}
// 钉钉不支持 , 鸿蒙是异步
if (!ctx.measureText || getDeviceInfo().osName == 'harmonyos') {
ctx._measureText = ctx.measureText
const strLen = (str) => {
let len = 0;
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) {
len++;
} else {
len += 2;
}
}
return len;
}
ctx.measureText = (text, font) => {
let fontSize = ctx?.state?.fontSize || 12;
if (font) {
fontSize = parseInt(font.match(/([\d\.]+)px/)[1])
}
fontSize /= 2;
let isBold = fontSize >= 16;
const widthFactor = isBold ? 1.3 : 1;
// ctx._measureText(text, (res) => {})
return {
width: strLen(text) * fontSize * widthFactor
};
}
}
}
_initEvent(e) {
this.event = {};
const eventNames = [{
wxName: 'touchStart',
ecName: 'mousedown'
}, {
wxName: 'touchMove',
ecName: 'mousemove'
}, {
wxName: 'touchEnd',
ecName: 'mouseup'
}, {
wxName: 'touchEnd',
ecName: 'click'
}];
eventNames.forEach(name => {
this.event[name.wxName] = e => {
const touch = e.touches[0];
this.chart.getZr().handler.dispatch(name.ecName, {
zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
zrY: name.wxName === 'tap' ? touch.clientY : touch.y
});
};
});
}
set width(w) {
this.canvasNode.width = w
}
set height(h) {
this.canvasNode.height = h
}
get width() {
return this.canvasNode.width || 0
}
get height() {
return this.canvasNode.height || 0
}
get ctx() {
return cacheChart[this.canvasId]['ctx'] || null
}
set chart(chart) {
cacheChart[this.canvasId]['chart'] = chart
}
get chart() {
return cacheChart[this.canvasId]['chart'] || null
}
}
export function dispatch(name, {x,y, wheelDelta}) {
this.dispatch(name, {
zrX: x,
zrY: y,
zrDelta: wheelDelta,
preventDefault: () => {},
stopPropagation: () =>{}
});
}
export function setCanvasCreator(echarts, {canvas, node}) {
// echarts.setCanvasCreator(() => canvas);
if(echarts && !echarts.registerPreprocessor) {
return console.warn('echarts 版本不对或未传入echarts,vue3请使用esm格式')
}
echarts.registerPreprocessor(option => {
if (option && option.series) {
if (option.series.length > 0) {
option.series.forEach(series => {
series.progressive = 0;
});
} else if (typeof option.series === 'object') {
option.series.progressive = 0;
}
}
});
function loadImage(src, onload, onerror) {
let img = null
if(node && node.createImage) {
img = node.createImage()
img.onload = onload.bind(img);
img.onerror = onerror.bind(img);
img.src = src;
return img
} else {
img = new Image()
img.onload = onload.bind(img)
img.onerror = onerror.bind(img);
img.src = src
return img
}
}
if(echarts.setPlatformAPI) {
echarts.setPlatformAPI({
loadImage: canvas.setChart ? loadImage : null,
createCanvas(){
const key = 'createOffscreenCanvas'
return uni.canIUse(key) && uni[key] ? uni[key]({type: '2d'}) : canvas
}
})
}
}
\ No newline at end of file \ No newline at end of file
<template>
<!-- #ifdef APP -->
<web-view class="lime-echart" ref="chartRef" @load="loaded" :style="[customStyle]"
:webview-styles="[webviewStyles]" src="/uni_modules/lime-echart/static/uvue.html?v=10112">
</web-view>
<!-- #endif -->
<!-- #ifdef H5 -->
<div class="lime-echart" ref="chartRef"></div>
<!-- #endif -->
<!-- #ifndef H5 || APP-->
<canvas class="lime-echart" :id="canvasid" :canvas-id="canvasid"
@touchstart="touchstart"
@touchmove="touchmove"
@touchend="touchend">
</canvas>
<!-- #endif -->
</template>
<script lang="uts" setup>
// @ts-nocheck
import { getCurrentInstance, nextTick } from "vue";
import { Echarts } from './uvue';
// #ifdef WEB
import { dispatch } from './canvas';
// #endif
// #ifndef APP || WEB
import {Canvas, setCanvasCreator, dispatch} from './canvas';
import {wrapTouch, convertTouchesToArray, devicePixelRatio ,sleep, canIUseCanvas2d, getRect} from './utils';
// #endif
type EchartsResolve = (value : Echarts) => void
defineOptions({
name: 'l-echart'
})
const emits = defineEmits(['finished'])
const props = defineProps({
// #ifdef APP
webviewStyles: {
type: Object
},
customStyle: {
type: Object
},
// #endif
// #ifndef APP
webviewStyles: {
type: Object
},
customStyle: {
type: [String, Object]
},
// #endif
isDisableScroll: {
type: Boolean,
default: false
},
isClickable: {
type: Boolean,
default: true
},
enableHover: {
type: Boolean,
default: false
},
beforeDelay: {
type: Number,
default: 30
}
})
const instance = getCurrentInstance()!;
const canvasid = `lime-echart-${instance.uid}`
const finished = ref(false)
const map = [] as EchartsResolve[]
const callbackMap = [] as EchartsResolve[]
// let context = null as UniWebViewElement | null
let chart = null as Echarts | null
let chartRef = ref<UniWebViewElement | null>(null)
const trigger = () => {
// #ifdef APP
if (finished.value) {
if (chart == null) {
chart = new Echarts(chartRef.value!)
}
while (map.length > 0) {
const resolve = map.pop() as EchartsResolve
resolve(chart!)
}
}
// #endif
// #ifndef APP
while (map.length > 0) {
if(chart != null){
const resolve = map.pop() as EchartsResolve
resolve(chart!)
}
}
// #endif
if(chart != null){
while(callbackMap.length > 0){
const callback = callbackMap.pop() as EchartsResolve
callback(chart!)
}
}
}
// #ifdef APP
const loaded = (event : UniWebViewLoadEvent) => {
event.stopPropagation()
event.preventDefault()
finished.value = true
trigger()
emits('finished')
}
// #endif
const _next = () : boolean => {
if (chart == null) {
console.warn(`组件还未初始化,请先使用 init`)
return true
}
return false
}
const setOption = (option : UTSJSONObject) => {
if (_next()) return
chart!.setOption(option);
}
const showLoading = () => {
if (_next()) return
chart!.showLoading();
}
const hideLoading = () => {
if (_next()) return
chart!.hideLoading();
}
const clear = () => {
if (_next()) return
chart!.clear();
}
const dispose = () => {
if (_next()) return
chart!.dispose();
}
const resize = (size : UTSJSONObject) => {
if (_next()) return
chart!.resize(size);
}
const canvasToTempFilePath = (opt : UTSJSONObject) => {
if (_next()) return
chart!.canvasToTempFilePath(opt);
}
// #ifdef APP
function init(callback : ((chart : Echarts) => void) | null) : Promise<Echarts> {
if(callback!=null){
callbackMap.push(callback)
}
return new Promise<Echarts>((resolve) => {
map.push(resolve)
trigger()
})
}
// #endif
// #ifndef APP
// #ifndef WEB
let use2dCanvas = canIUseCanvas2d()
const getContext = async () =>{
return getRect(`#${canvasid}`, {context: instance.proxy!, type: use2dCanvas ? 'fields': 'boundingClientRect'}).then(res => {
if(res) {
let dpr = uni.getWindowInfo().pixelRatio
let {width, height, node} = res
let canvas;
if(node) {
const ctx = node.getContext('2d');
canvas = new Canvas(ctx, instance.proxy, true, node);
} else {
const ctx = uni.createCanvasContext(canvasid, instance.proxy);
canvas = new Canvas(ctx, instance.proxy, false);
}
return { canvas, width, height, devicePixelRatio: dpr, node };
} else {
return {}
}
})
}
// #endif
const getTouch = (e) => {
const touches = e.touches[0]
// #ifdef WEB
const rect = chart!.getZr().dom.getBoundingClientRect();
const touch = {
x: touches.clientX - rect.left,
y: touches.clientY - rect.top
}
// #endif
// #ifndef WEB
const touch = {
x: touches.x,
y: touches.y
}
// #endif
return touch
}
const touchstart = (e) => {
if(chart == null) return
const handler = chart.getZr().handler;
const touch = getTouch(e)
dispatch.call(handler, 'mousedown', touch)
dispatch.call(handler, 'click', touch)
}
const touchmove = (e) => {
if(chart == null) return
const handler = chart.getZr().handler;
const touch = getTouch(e)
dispatch.call(handler, 'mousemove', touch)
// const rect = chart.getZr().dom.getBoundingClientRect()
// handler.dispatch('mousemove', {
// zrX: e.touches[0].clientX - rect.left,
// zrY: e.touches[0].clientY - rect.top
// })
}
const touchend = (e) => {
if(chart == null) return
const handler = chart.getZr().handler;
const touch = {
x: 999999999,
y: 999999999
}
dispatch.call(handler, 'mousemove', touch)
dispatch.call(handler, 'touchend', touch)
}
async function init(echarts: any, ...args: any[]): Promise<Echarts>{
if(echarts == null){
console.error('请确保已经引入了 ECharts 库');
return Promise.reject('请确保已经引入了 ECharts 库');
}
let theme:string|null=null
let opts={}
let callback:Function|null=null;
args.forEach(item =>{
if(typeof item === 'function') {
callback = item
} else if(['string'].includes(typeof item)){
theme = item
} else if(typeof item === 'object'){
opts = item
}
})
// #ifdef WEB
chart = echarts.init(chartRef.value, theme, opts)
window.addEventListener('touchstart', touchstart)
window.addEventListener('touchmove', touchmove)
window.addEventListener('touchend', touchend)
// #endif
// #ifndef WEB
let config = await getContext();
setCanvasCreator(echarts, config)
chart = echarts.init(config.canvas, theme, Object.assign({}, config, opts))
// #endif
console.log('chart', chart)
if(callback!=null && typeof callback == 'function'){
callbackMap.push(callback)
}
return new Promise<Echarts>((resolve) => {
map.push(resolve)
trigger()
})
}
onMounted(()=>{
nextTick(()=>{
finished.value = true
trigger()
emits('finished')
})
})
onUnmounted(()=>{
// #ifdef WEB
window.removeEventListener('touchstart', touchstart)
window.removeEventListener('touchmove', touchmove)
window.removeEventListener('touchend', touchend)
// #endif
})
// #endif
defineExpose({
init,
setOption,
showLoading,
hideLoading,
clear,
dispose,
resize,
canvasToTempFilePath
})
</script>
<style lang="scss">
.lime-echart {
flex: 1;
width: 100%;
}
</style>
\ No newline at end of file \ No newline at end of file
<template>
<view class="lime-echart" :style="[customStyle]" v-if="canvasId" ref="limeEchart" :aria-label="ariaLabel">
<!-- #ifndef APP-NVUE -->
<canvas
class="lime-echart__canvas"
v-if="use2dCanvas"
type="2d"
:id="canvasId"
:style="canvasStyle"
:disable-scroll="isDisableScroll"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
/>
<canvas
class="lime-echart__canvas"
v-else
:width="nodeWidth"
:height="nodeHeight"
:style="canvasStyle"
:canvas-id="canvasId"
:id="canvasId"
:disable-scroll="isDisableScroll"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
/>
<view class="lime-echart__mask"
v-if="isPC"
@mousedown="touchStart"
@mousemove="touchMove"
@mouseup="touchEnd"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd">
</view>
<canvas v-if="isOffscreenCanvas" :style="offscreenStyle" :canvas-id="offscreenCanvasId"></canvas>
<!-- #endif -->
<!-- #ifdef APP-NVUE -->
<web-view
class="lime-echart__canvas"
:id="canvasId"
:style="canvasStyle"
:webview-styles="webviewStyles"
ref="webview"
src="/uni_modules/lime-echart/static/uvue.html?v=1"
@pagefinish="finished = true"
@onPostMessage="onMessage"
></web-view>
<!-- #endif -->
</view>
</template>
<script>
// @ts-nocheck
// #ifndef APP-NVUE
import {Canvas, setCanvasCreator, dispatch} from './canvas';
import {wrapTouch, convertTouchesToArray, devicePixelRatio ,sleep, canIUseCanvas2d, getRect, getDeviceInfo} from './utils';
// #endif
// #ifdef APP-NVUE
import { base64ToPath, sleep } from './utils';
import {Echarts} from './nvue'
// #endif
const charts = {}
const echartsObj = {}
/**
* LimeChart 图表
* @description 全端兼容的eCharts
* @tutorial https://ext.dcloud.net.cn/plugin?id=4899
* @property {String} customStyle 自定义样式
* @property {String} type 指定 canvas 类型
* @value 2d 使用canvas 2d,部分小程序支持
* @value '' 使用原生canvas,会有层级问题
* @value bottom right 不缩放图片,只显示图片的右下边区域
* @property {Boolean} isDisableScroll
* @property {number} beforeDelay = [30] 延迟初始化 (毫秒)
* @property {Boolean} enableHover PC端使用鼠标悬浮
* @event {Function} finished 加载完成触发
*/
export default {
name: 'lime-echart',
props: {
// #ifdef MP-WEIXIN || MP-TOUTIAO
type: {
type: String,
default: '2d'
},
// #endif
// #ifdef APP-NVUE
webviewStyles: Object,
// hybrid: Boolean,
// #endif
customStyle: String,
isDisableScroll: Boolean,
isClickable: {
type: Boolean,
default: true
},
enableHover: Boolean,
beforeDelay: {
type: Number,
default: 30
},
landscape: Boolean
},
data() {
return {
// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
use2dCanvas: true,
// #endif
// #ifndef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
use2dCanvas: false,
// #endif
ariaLabel: '图表',
width: null,
height: null,
nodeWidth: null,
nodeHeight: null,
// canvasNode: null,
config: {},
inited: false,
finished: false,
file: '',
platform: '',
isPC: false,
isDown: false,
isOffscreenCanvas: false,
offscreenWidth: 0,
offscreenHeight: 0,
};
},
computed: {
rootStyle() {
if(this.landscape) {
return `transform: translate(-50%,-50%) rotate(90deg); top:50%; left:50%;`
}
},
canvasId() {
return `lime-echart${this._ && this._.uid || this._uid}`
},
offscreenCanvasId() {
return `${this.canvasId}_offscreen`
},
offscreenStyle() {
return `width:${this.offscreenWidth}px;height: ${this.offscreenHeight}px; position: fixed; left: 99999px; background: red`
},
canvasStyle() {
return this.rootStyle + (this.width && this.height ? ('width:' + this.width + 'px;height:' + this.height + 'px') : '')
}
},
// #ifndef VUE3
beforeDestroy() {
this.clear()
this.dispose()
// #ifdef H5
if(this.isPC) {
document.removeEventListener('mousewheel', this.mousewheel)
}
// #endif
},
// #endif
// #ifdef VUE3
beforeUnmount() {
this.clear()
this.dispose()
// #ifdef H5
if(this.isPC) {
document.removeEventListener('mousewheel', this.mousewheel)
}
// #endif
},
// #endif
created() {
// #ifdef H5
if(!('ontouchstart' in window)) {
this.isPC = true
document.addEventListener('mousewheel', this.mousewheel)
}
// #endif
// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
// const { platform } = uni.getSystemInfoSync();
const { platform } = getDeviceInfo();
this.isPC = /windows/i.test(platform)
// #endif
this.use2dCanvas = this.type === '2d' && canIUseCanvas2d()
},
mounted() {
this.$nextTick(() => {
this.$emit('finished')
})
},
methods: {
// #ifdef APP-NVUE
onMessage(e) {
const detail = e?.detail?.data[0] || null;
const data = detail?.data
const key = detail?.event
const options = data?.options
const event = data?.event
const file = detail?.file
if (key == 'log' && data) {
console.log(data)
}
if(event) {
this.chart.dispatchAction(event.replace(/"/g,''), options)
}
if(file) {
thie.file = file
}
},
// #endif
setChart(callback) {
if(!this.chart) {
console.warn(`组件还未初始化,请先使用 init`)
return
}
if(typeof callback === 'function' && this.chart) {
callback(this.chart);
}
// #ifdef APP-NVUE
if(typeof callback === 'function') {
this.$refs.webview.evalJs(`setChart(${JSON.stringify(callback.toString())}, ${JSON.stringify(this.chart.options)})`);
}
// #endif
},
setOption() {
if (!this.chart || !this.chart.setOption) {
console.warn(`组件还未初始化,请先使用 init`)
return
}
this.chart.setOption(...arguments);
},
showLoading() {
if(this.chart) {
this.chart.showLoading(...arguments)
}
},
hideLoading() {
if(this.chart) {
this.chart.hideLoading()
}
},
clear() {
if(this.chart) {
this.chart.clear()
}
},
dispose() {
if(this.chart) {
this.chart.dispose()
}
},
resize(size) {
if(size && size.width && size.height) {
this.height = size.height
this.width = size.width
if(this.chart) {this.chart.resize(size)}
} else {
this.$nextTick(() => {
uni.createSelectorQuery()
.in(this)
.select(`.lime-echart`)
.boundingClientRect()
.exec(res => {
if (res) {
let { width, height } = res[0];
this.width = width = width || 300;
this.height = height = height || 300;
this.chart.resize({width, height})
}
});
})
}
},
canvasToTempFilePath(args = {}) {
// #ifndef APP-NVUE
const { use2dCanvas, canvasId } = this;
return new Promise((resolve, reject) => {
const copyArgs = Object.assign({
canvasId,
success: resolve,
fail: reject
}, args);
if (use2dCanvas) {
delete copyArgs.canvasId;
copyArgs.canvas = this.canvasNode;
}
uni.canvasToTempFilePath(copyArgs, this);
});
// #endif
// #ifdef APP-NVUE
this.file = ''
this.$refs.webview.evalJs(`canvasToTempFilePath()`);
return new Promise((resolve, reject) => {
this.$watch('file', async (file) => {
if(file) {
const tempFilePath = await base64ToPath(file)
resolve(args.success({tempFilePath}))
} else {
reject(args.fail({error: ``}))
}
})
})
// #endif
},
async init(echarts, ...args) {
// #ifndef APP-NVUE
if(args && args.length == 0 && !echarts) {
console.error('缺少参数:init(echarts, theme?:string, opts?: object, callback?: function)')
return
}
// #endif
let theme=null,opts={},callback;
Array.from(arguments).forEach(item => {
if(typeof item === 'function') {
callback = item
}
if(['string'].includes(typeof item)) {
theme = item
}
if(typeof item === 'object') {
opts = item
}
})
if(this.beforeDelay) {
await sleep(this.beforeDelay)
}
let config = await this.getContext();
// #ifndef APP-NVUE
setCanvasCreator(echarts, config)
try {
this.chart = echarts.init(config.canvas, theme, Object.assign({}, config, opts))
if(typeof callback === 'function') {
callback(this.chart)
} else {
return this.chart
}
} catch(e) {
console.error(e.messges)
return null
}
// #endif
// #ifdef APP-NVUE
this.chart = new Echarts(this.$refs.webview)
this.$refs.webview.evalJs(`init(null, null, ${JSON.stringify(opts)}, ${theme})`)
if(callback) {
callback(this.chart)
} else {
return this.chart
}
// #endif
},
getContext() {
// #ifdef APP-NVUE
if(this.finished) {
return Promise.resolve(this.finished)
}
return new Promise(resolve => {
this.$watch('finished', (val) => {
if(val) {
resolve(this.finished)
}
})
})
// #endif
// #ifndef APP-NVUE
return getRect(`#${this.canvasId}`, {context: this, type: this.use2dCanvas ? 'fields': 'boundingClientRect'}).then(res => {
if(res) {
let dpr = devicePixelRatio
let {width, height, node} = res
let canvas;
this.width = width = width || 300;
this.height = height = height || 300;
if(node) {
const ctx = node.getContext('2d');
canvas = new Canvas(ctx, this, true, node);
this.canvasNode = node
} else {
// #ifdef MP-TOUTIAO
dpr = !this.isPC ? devicePixelRatio : 1// 1.25
// #endif
// #ifndef MP-ALIPAY || MP-TOUTIAO
dpr = this.isPC ? devicePixelRatio : 1
// #endif
// #ifdef MP-ALIPAY || MP-LARK
dpr = devicePixelRatio
// #endif
// #ifdef WEB
dpr = 1
// #endif
this.rect = res
this.nodeWidth = width * dpr;
this.nodeHeight = height * dpr;
const ctx = uni.createCanvasContext(this.canvasId, this);
canvas = new Canvas(ctx, this, false);
}
return { canvas, width, height, devicePixelRatio: dpr, node };
} else {
return {}
}
})
// #endif
},
// #ifndef APP-NVUE
getRelative(e, touches) {
let { clientX, clientY } = e
if(!(clientX && clientY) && touches && touches[0]) {
clientX = touches[0].clientX
clientY = touches[0].clientY
}
return {x: clientX - this.rect.left, y: clientY - this.rect.top, wheelDelta: e.wheelDelta || 0}
},
getTouch(e, touches) {
const {x} = touches && touches[0] || {}
const touch = x ? touches[0] : this.getRelative(e, touches);
if(this.landscape) {
[touch.x, touch.y] = [touch.y, this.height - touch.x]
}
return touch;
},
touchStart(e) {
this.isDown = true
const next = () => {
const touches = convertTouchesToArray(e.touches)
if(this.chart) {
const touch = this.getTouch(e, touches)
this.startX = touch.x
this.startY = touch.y
this.startT = new Date()
const handler = this.chart.getZr().handler;
dispatch.call(handler, 'mousedown', touch)
dispatch.call(handler, 'mousemove', touch)
handler.processGesture(wrapTouch(e), 'start');
clearTimeout(this.endTimer);
}
}
if(this.isPC) {
getRect(`#${this.canvasId}`, {context: this}).then(res => {
this.rect = res
next()
})
return
}
next()
},
touchMove(e) {
if(this.isPC && this.enableHover && !this.isDown) {this.isDown = true}
const touches = convertTouchesToArray(e.touches)
if (this.chart && this.isDown) {
const handler = this.chart.getZr().handler;
dispatch.call(handler, 'mousemove', this.getTouch(e, touches))
handler.processGesture(wrapTouch(e), 'change');
}
},
touchEnd(e) {
this.isDown = false
if (this.chart) {
const touches = convertTouchesToArray(e.changedTouches)
const {x} = touches && touches[0] || {}
const touch = (x ? touches[0] : this.getRelative(e, touches)) || {};
if(this.landscape) {
[touch.x, touch.y] = [touch.y, this.height - touch.x]
}
const handler = this.chart.getZr().handler;
const isClick = Math.abs(touch.x - this.startX) < 10 && new Date() - this.startT < 200;
dispatch.call(handler, 'mouseup', touch)
handler.processGesture(wrapTouch(e), 'end');
if(isClick) {
dispatch.call(handler, 'click', touch)
} else {
this.endTimer = setTimeout(() => {
dispatch.call(handler, 'mousemove', {x: 999999999,y: 999999999});
dispatch.call(handler, 'mouseup', {x: 999999999,y: 999999999});
},50)
}
}
},
// #endif
// #ifdef H5
mousewheel(e){
if(this.chart) {
// dispatch.call(this.chart.getZr().handler, 'mousewheel', this.getTouch(e))
}
}
// #endif
}
};
</script>
<style>
.lime-echart {
position: relative;
/* #ifndef APP-NVUE */
width: 100%;
height: 100%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
.lime-echart__canvas {
/* #ifndef APP-NVUE */
width: 100%;
height: 100%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
/* #ifndef APP-NVUE */
.lime-echart__mask {
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
z-index: 1;
}
/* #endif */
</style>
export class Echarts {
eventMap = new Map()
constructor(webview) {
this.webview = webview
this.options = null
}
setOption() {
this.options = arguments
this.webview.evalJs(`setOption(${JSON.stringify(arguments)})`);
}
getOption() {
return this.options
}
showLoading() {
this.webview.evalJs(`showLoading(${JSON.stringify(arguments)})`);
}
hideLoading() {
this.webview.evalJs(`hideLoading()`);
}
clear() {
this.webview.evalJs(`clear()`);
}
dispose() {
this.webview.evalJs(`dispose()`);
}
resize(size) {
if(size) {
this.webview.evalJs(`resize(${JSON.stringify(size)})`);
} else {
this.webview.evalJs(`resize()`);
}
}
on(type, ...args) {
const query = args[0]
const useQuery = query && typeof query != 'function'
const param = useQuery ? [type, query] : [type]
const key = `${type}${useQuery ? JSON.stringify(query): '' }`
const callback = useQuery ? args[1]: args[0]
if(typeof callback == 'function'){
this.eventMap.set(key, callback)
}
this.webview.evalJs(`on(${JSON.stringify(param)})`);
console.warn('nvue 暂不支持事件')
}
dispatchAction(type, options){
const handler = this.eventMap.get(type)
if(handler){
handler(options)
}
}
}
\ No newline at end of file \ No newline at end of file
// @ts-nocheck
/**
* 获取设备基础信息
*
* @see [uni.getDeviceInfo](https://uniapp.dcloud.net.cn/api/system/getDeviceInfo.html)
*/
export function getDeviceInfo() {
if (uni.getDeviceInfo && uni.canIUse('getDeviceInfo')) {
return uni.getDeviceInfo();
} else {
return uni.getSystemInfoSync();
}
}
/**
* 获取窗口信息
*
* @see [uni.getWindowInfo](https://uniapp.dcloud.net.cn/api/system/getWindowInfo.html)
*/
export function getWindowInfo() {
if (uni.getWindowInfo && uni.canIUse('getWindowInfo')) {
return uni.getWindowInfo();
} else {
return uni.getSystemInfoSync();
}
}
/**
* 获取APP基础信息
*
* @see [uni.getAppBaseInfo](https://uniapp.dcloud.net.cn/api/system/getAppBaseInfo.html)
*/
export function getAppBaseInfo() {
if (uni.getAppBaseInfo && uni.canIUse('getAppBaseInfo')) {
return uni.getAppBaseInfo();
} else {
return uni.getSystemInfoSync();
}
}
// #ifndef APP-NVUE
// 计算版本
export function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i], 10)
const num2 = parseInt(v2[i], 10)
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
// const systemInfo = uni.getSystemInfoSync();
function gte(version) {
// 截止 2023-03-22 mac pc小程序不支持 canvas 2d
// let {
// SDKVersion,
// platform
// } = systemInfo;
const { platform } = getDeviceInfo();
let { SDKVersion } = getAppBaseInfo();
// #ifdef MP-ALIPAY
SDKVersion = my.SDKVersion
// #endif
// #ifdef MP-WEIXIN
return platform !== 'mac' && compareVersion(SDKVersion, version) >= 0;
// #endif
return compareVersion(SDKVersion, version) >= 0;
}
export function canIUseCanvas2d() {
// #ifdef MP-WEIXIN
return gte('2.9.0');
// #endif
// #ifdef MP-ALIPAY
return gte('2.7.0');
// #endif
// #ifdef MP-TOUTIAO
return gte('1.78.0');
// #endif
return false
}
export function convertTouchesToArray(touches) {
// 如果 touches 是一个数组,则直接返回它
if (Array.isArray(touches)) {
return touches;
}
// 如果touches是一个对象,则转换为数组
if (typeof touches === 'object' && touches !== null) {
return Object.values(touches);
}
// 对于其他类型,直接返回它
return touches;
}
export function wrapTouch(event) {
event.touches = convertTouchesToArray(event.touches)
for (let i = 0; i < event.touches.length; ++i) {
const touch = event.touches[i];
touch.offsetX = touch.x;
touch.offsetY = touch.y;
}
return event;
}
// export const devicePixelRatio = uni.getSystemInfoSync().pixelRatio
export const devicePixelRatio = getWindowInfo().pixelRatio;
// #endif
// #ifdef APP-NVUE
export function base64ToPath(base64) {
return new Promise((resolve, reject) => {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
const bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, () => {
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'))
}
const time = new Date().getTime();
const filePath = `_doc/uniapp_temp/${time}.${format}`
bitmap.save(filePath, {},
() => {
bitmap.clear()
resolve(filePath)
},
(error) => {
bitmap.clear()
console.error(`${JSON.stringify(error)}`)
reject(error)
})
}, (error) => {
bitmap.clear()
console.error(`${JSON.stringify(error)}`)
reject(error)
})
})
}
// #endif
export function sleep(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(true)
}, time)
})
}
export function getRect(selector, options = {}) {
const typeDefault = 'boundingClientRect'
const {
context,
type = typeDefault
} = options
return new Promise((resolve, reject) => {
const dom = uni.createSelectorQuery().in(context).select(selector);
const result = (rect) => {
if (rect) {
resolve(rect)
} else {
reject()
}
}
if (type == typeDefault) {
dom[type](result).exec()
} else {
dom[type]({
node: true,
size: true,
rect: true
}, result).exec()
}
});
};
\ No newline at end of file \ No newline at end of file
// @ts-nocheck
// #ifdef APP
type EchartsEventHandler = (event: UTSJSONObject)=>void
// type EchartsTempResolve = (obj : UTSJSONObject) => void
// type EchartsTempOptions = UTSJSONObject
export class Echarts {
options: UTSJSONObject = {} as UTSJSONObject
context: UniWebViewElement
eventMap: Map<string, EchartsEventHandler> = new Map()
private temp: UTSJSONObject[] = []
constructor(context: UniWebViewElement){
this.context = context
this.init()
}
init(){
this.context.evalJS(`init(null, null, ${JSON.stringify({})})`)
this.context.addEventListener('message', (e : UniWebViewMessageEvent) => {
// event.stopPropagation()
// event.preventDefault()
const detail = e.detail.data[0]
const file = detail.getString('file')
const data = detail.get('data')
const key = detail.getString('event')
const options = typeof data == 'object' ? (data as UTSJSONObject).getJSON('options'): null
const event = typeof data == 'object' ? (data as UTSJSONObject).getString('event'): null
if (key == 'log' && data != null) {
console.log(data)
}
if (event != null && options != null) {
this.dispatchAction(event.replace(/"/g,''), options)
}
if(file != null){
while (this.temp.length > 0) {
const opt = this.temp.pop()
const success = opt?.get('success')
if(typeof success == 'function'){
success as (res: UTSJSONObject) => void
success({tempFilePath: file})
}
}
}
})
}
setOption(option: UTSJSONObject){
this.options = option;
this.context.evalJS(`setOption(${JSON.stringify([option])})`)
}
setOption(option: UTSJSONObject, notMerge: boolean = false, lazyUpdate: boolean = false){
this.options = option;
this.context.evalJS(`setOption(${JSON.stringify([option, notMerge, lazyUpdate])})`)
}
setOption(option: UTSJSONObject, notMerge: UTSJSONObject){
this.options = option;
this.context.evalJS(`setOption(${JSON.stringify([option, notMerge])})`)
}
getOption(): UTSJSONObject {
return this.options
}
showLoading(){
this.context.evalJS(`showLoading(${JSON.stringify([] as any[])})`);
}
showLoading(type: string, opts: UTSJSONObject){
this.context.evalJS(`showLoading(${JSON.stringify([type, opts])})`);
}
hideLoading(){
this.context.evalJS(`hideLoading()`);
}
clear(){
this.context.evalJS(`clear()`);
}
dispose(){
this.context.evalJS(`dispose()`);
}
resize(size:UTSJSONObject){
setTimeout(()=>{
this.context.evalJS(`resize(${JSON.stringify(size)})`);
},0)
}
resize(){
setTimeout(()=>{
this.context.evalJS(`resize()`);
},10)
}
on(type:string, query: any, callback: EchartsEventHandler) {
const key = `${type}${JSON.stringify(query)}`
if(typeof callback == 'function'){
this.eventMap.set(key, callback)
}
this.context.evalJS(`on(${JSON.stringify([type, query])})`);
console.warn('uvue 暂不支持事件')
}
on(type:string, callback: EchartsEventHandler) {
const key = `${type}`
if(typeof callback == 'function'){
this.eventMap.set(key, callback)
}
this.context.evalJS(`on(${JSON.stringify([type])})`);
console.warn('uvue 暂不支持事件')
}
dispatchAction(type:string, options: UTSJSONObject){
const handler = this.eventMap.get(type)
if(handler!=null){
handler(options)
}
}
canvasToTempFilePath(opt: UTSJSONObject){
// this.context.evalJS(`on(${JSON.stringify(opt)})`);
this.context.evalJS(`canvasToTempFilePath(${JSON.stringify(opt)})`);
this.temp.push(opt)
}
}
// #endif
// #ifndef APP
export class Echarts {
constructor() {}
setOption(option: UTSJSONObject): void
isDisposed(): boolean;
clear(): void;
resize(size:UTSJSONObject): void;
resize(): void;
canvasToTempFilePath(opt : UTSJSONObject): void;
dispose(): void;
showLoading(cfg?: UTSJSONObject): void;
showLoading(name?: string, cfg?: UTSJSONObject): void;
hideLoading(): void;
getZr(): any
}
// #endif
\ No newline at end of file \ No newline at end of file
<template>
<view style="width: 100%; height: 408px;">
<l-echart ref="chartRef" @finished="init"></l-echart>
</view>
</template>
<script>
export default {
data() {
return {
showTip: false,
option: {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0
},
renderMode: 'richText',
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
}
},
mounted() {
console.log('lime echarts nvue')
},
methods: {
init() {
const chartRef = this.$refs['chartRef']
chartRef.init(chart => {
chart.setOption(this.option);
setTimeout(()=>{
const option = {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0
},
renderMode: 'richText',
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
chart.setOption(option);
},1000)
})
},
save() {
// this.$refs.chart.canvasToTempFilePath({
// success(res) {
// console.log('res::::', res)
// }
// })
}
}
}
</script>
<style>
</style>
\ No newline at end of file \ No newline at end of file
<template>
<view style="width: 100%; height: 408px;">
<l-echart ref="chartRef" @finished="init"></l-echart>
</view>
</template>
<script lang="uts" setup>
// @ts-nocheck
// #ifndef APP
import * as echarts from 'echarts/dist/echarts.esm.js'
// #endif
const chartRef = ref<LEchartComponentPublicInstance|null>(null)
const option = {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0
},
renderMode: 'richText',
},
// formatter: async (params: any) => {
// console.log('params', params)
// return 1
// },
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
const init = async () =>{
if(chartRef.value== null) return
// #ifdef APP
const chart = await chartRef.value!.init(null)
// #endif
// #ifndef APP
const chart = await chartRef.value!.init(echarts, null)
// #endif
chart.setOption(option)
chart.on('mouseover', function (params) {
console.log('params', params);
});
// setTimeout(()=> {
// const option1 = {
// tooltip: {
// trigger: 'axis',
// // shadowBlur: 0,
// textStyle: {
// textShadowBlur: 0
// },
// renderMode: 'richText',
// },
// legend: {
// data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
// },
// grid: {
// left: '3%',
// right: '4%',
// bottom: '3%',
// containLabel: true
// },
// xAxis: {
// type: 'category',
// boundaryGap: false,
// data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
// },
// yAxis: {
// type: 'value'
// },
// series: [
// {
// name: '邮件营销',
// type: 'line',
// stack: '总量',
// data: [820, 132, 101, 134, 90, 230, 210]
// },
// {
// name: '联盟广告',
// type: 'line',
// stack: '总量',
// data: [220, 182, 191, 234, 290, 330, 310]
// },
// {
// name: '视频广告',
// type: 'line',
// stack: '总量',
// data: [950, 232, 201, 154, 190, 330, 410]
// },
// {
// name: '直接访问',
// type: 'line',
// stack: '总量',
// data: [320, 332, 301, 334, 390, 330, 320]
// },
// {
// name: '搜索引擎',
// type: 'line',
// stack: '总量',
// data: [820, 932, 901, 934, 1290, 1330, 1320]
// }
// ]
// }
// chart.setOption(option1)
// },1000)
}
</script>
<style>
</style>
\ No newline at end of file \ No newline at end of file
<template>
<view>
<view style="height: 750rpx; position: relative">
<l-echart ref="chart" @finished="init"></l-echart>
<view
class="customTooltips"
:style="{ left: position[0] + 'px', top: position[1] + 'px' }"
v-if="params.length && position.length && showTip"
>
<view>这是个自定的tooltips</view>
<view>{{ params[0]['axisValue'] }}</view>
<view v-for="item in params">
<view>
<text>{{ item.seriesName }}</text>
<text>{{ item.value }}</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
// nvue 不需要引入
// #ifdef VUE2
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
// #endif
// #ifdef VUE3
// #ifdef MP
// 由于vue3 使用vite 不支持umd格式的包,小程序依然可以使用,但需要使用require
const echarts = require('../../static/echarts.min')
// #endif
// #ifndef MP
// 由于 vue3 使用vite 不支持umd格式的包,故引入npm的包
import * as echarts from 'echarts/dist/echarts.esm'
// #endif
// #endif
export default {
data() {
return {
showTip: false,
position: [],
params: [],
option: {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0,
},
renderMode: 'richText',
position: (point, params, dom, rect, size) => {
// 假设自定义的tooltips尺寸
const box = [170, 170]
// 偏移
const offsetX = point[0] < size.viewSize[0] / 2 ? 20 : -box[0] - 20
const offsetY = point[1] < size.viewSize[1] / 2 ? 20 : -box[1] - 20
const x = point[0] + offsetX
const y = point[1] + offsetY
this.position = [x, y]
this.params = params
},
formatter: (params, ticket, callback) => {},
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎'],
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true,
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
},
yAxis: {
type: 'value',
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210],
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310],
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410],
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320],
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320],
},
],
},
}
},
methods: {
init() {
// init(echarts, theme?:string, opts?:{}, chart => {})
// echarts 必填, 非nvue必填,nvue不用填
// theme 可选,应用的主题,目前只支持名称,如:'dark'
// opts = { // 可选
// locale?: string // 从 `5.0.0` 开始支持
// }
// chart => {} , callback 返回图表实例
// setTimeout(()=>{
// this.$refs.chart.init(echarts, chart => {
// chart.setOption(this.option);
// });
// },300)
this.$refs.chart.init(echarts, (chart) => {
chart.setOption(this.option)
// 监听tooltip显示事件
chart.on('showTip', (params) => {
this.showTip = true
console.log('showTip::')
})
chart.on('hideTip', (params) => {
setTimeout(() => {
this.showTip = false
}, 300)
})
setTimeout(() => {
const option = {
tooltip: {
trigger: 'axis',
// shadowBlur: 0,
textStyle: {
textShadowBlur: 0,
},
renderMode: 'richText',
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎'],
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true,
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
},
yAxis: {
type: 'value',
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [1120, 132, 101, 134, 90, 230, 210],
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310],
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 632, 201, 154, 190, 330, 410],
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [820, 332, 301, 334, 390, 330, 320],
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320],
},
],
}
chart.setOption(option)
}, 1000)
})
},
save() {
this.$refs.chart.canvasToTempFilePath({
success(res) {
console.log('res::::', res)
},
})
},
},
}
</script>
<style>
.customTooltips {
position: absolute;
background-color: rgba(255, 255, 255, 0.8);
padding: 20rpx;
}
</style>
{
"id": "lime-echart",
"displayName": "echarts",
"version": "0.9.8",
"description": "echarts 全端兼容,一款使echarts图表能跑在uniapp各端中的插件, 支持uniapp/uniappx(web,ios,安卓)",
"keywords": [
"echarts",
"canvas",
"图表",
"可视化"
],
"repository": "https://gitee.com/liangei/lime-echart",
"engines": {
"HBuilderX": "^3.6.4"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "",
"type": "component-vue"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "n"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y",
"app-uvue": "y",
"app-harmony": "u"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
},
"dependencies": {
"echarts": "^5.4.1",
"zrender": "^5.4.3"
}
}
\ No newline at end of file \ No newline at end of file
# echarts 图表 <span style="font-size:16px;">👑👑👑👑👑 <span style="background:#ff9d00;padding:2px 4px;color:#fff;font-size:10px;border-radius: 3px;">全端</span></span>
> 一个基于 JavaScript 的开源可视化图表库 [查看更多](https://limeui.qcoon.cn/#/echart) <br>
> 基于 echarts 做了兼容处理,更多示例请访问 [uni示例](https://limeui.qcoon.cn/#/echart-example) | [官方示例](https://echarts.apache.org/examples/zh/index.html) <br>
## 平台兼容
| H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 头条小程序 | QQ 小程序 | App |
| --- | ---------- | ------------ | ---------- | ---------- | --------- | ---- |
| √ | √ | √ | √ | √ | √ | √ |
## 安装
- 第一步:在市场导入 [百度图表](https://ext.dcloud.net.cn/plugin?id=4899)
- 第二步:选择插件依赖:<br>
1、可以选插件内的`echarts`包或自定义包,自定义包[下载地址](https://echarts.apache.org/zh/builder.html)<br>
2、或者使用`npm`安装`echarts`
**注意**
* 🔔 echarts 5.3.0及以上
* 🔔 如果是 `cli` 项目请下载插件到`src`目录下的`uni_modules`,没有这个目录就创建一个
## 代码演示
### Vue2
- 引入依赖,可以是插件内提供或自己下载的[自定义包](https://echarts.apache.org/zh/builder.html),也可以是`npm`包
```html
<view style="width:750rpx; height:750rpx"><l-echart ref="chartRef" @finished="init"></l-echart></view>
```
```js
// 插件内的 三选一
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
// 自定义的 三选一 下载后放入项目的路径
import * as echarts from 'xxx/echarts.min'
// npm包 三选一 需要在控制台 输入命令:npm install echarts
import * as echarts from 'echarts'
```
```js
export default {
data() {
return {
option: {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
confine: true
},
legend: {
data: ['热度', '正面', '负面']
},
grid: {
left: 20,
right: 20,
bottom: 15,
top: 40,
containLabel: true
},
xAxis: [
{
type: 'value',
axisLine: {
lineStyle: {
color: '#999999'
}
},
axisLabel: {
color: '#666666'
}
}
],
yAxis: [
{
type: 'category',
axisTick: { show: false },
data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
axisLine: {
lineStyle: {
color: '#999999'
}
},
axisLabel: {
color: '#666666'
}
}
],
series: [
{
name: '热度',
type: 'bar',
label: {
normal: {
show: true,
position: 'inside'
}
},
data: [300, 270, 340, 344, 300, 320, 310],
},
{
name: '正面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true
}
},
data: [120, 102, 141, 174, 190, 250, 220]
},
{
name: '负面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true,
position: 'left'
}
},
data: [-20, -32, -21, -34, -90, -130, -110]
}
]
},
};
},
// 组件能被调用必须是组件的节点已经被渲染到页面上
methods: {
async init() {
// chart 图表实例不能存在data里
const chart = await this.$refs.chartRef.init(echarts);
chart.setOption(this.option)
}
}
}
```
### Vue3
- 小程序可以使用`require`引入插件内提供或自己下载的[自定义包](https://echarts.apache.org/zh/builder.html)
- `require`仅支持相对路径,不支持路径别名
- 非小程序使用 `npm` 包
```html
<view style="width:750rpx; height:750rpx"><l-echart ref="chartRef"></l-echart></view>
```
```js
// 小程序 二选一
// 插件内的 二选一
const echarts = require('../../uni_modules/lime-echart/static/echarts.min');
// 自定义的 二选一 下载后放入项目的路径
const echarts = require('xxx/xxx/echarts');
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 非小程序
// 需要在控制台 输入命令:npm install echarts
import * as echarts from 'echarts'
```
```js
const chartRef = ref(null)
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
confine: true
},
legend: {
data: ['热度', '正面', '负面']
},
grid: {
left: 20,
right: 20,
bottom: 15,
top: 40,
containLabel: true
},
xAxis: [
{
type: 'value',
axisLine: {
lineStyle: {
color: '#999999'
}
},
axisLabel: {
color: '#666666'
}
}
],
yAxis: [
{
type: 'category',
axisTick: { show: false },
data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
axisLine: {
lineStyle: {
color: '#999999'
}
},
axisLabel: {
color: '#666666'
}
}
],
series: [
{
name: '热度',
type: 'bar',
label: {
normal: {
show: true,
position: 'inside'
}
},
data: [300, 270, 340, 344, 300, 320, 310],
},
{
name: '正面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true
}
},
data: [120, 102, 141, 174, 190, 250, 220]
},
{
name: '负面',
type: 'bar',
stack: '总量',
label: {
normal: {
show: true,
position: 'left'
}
},
data: [-20, -32, -21, -34, -90, -130, -110]
}
]
};
onMounted( ()=>{
// 组件能被调用必须是组件的节点已经被渲染到页面上
setTimeout(async()=>{
if(!chartRef.value) return
const myChart = await chartRef.value.init(echarts)
myChart.setOption(option)
},300)
})
```
### Uvue
- Uvue和Nvue不需要引入`echarts`,因为它们的实现方式是`webview`
- uniapp x需要HBX 4.13以上
```html
<view style="width: 100%; height: 408px;">
<l-echart ref="chartRef" @finished="init"></l-echart>
</view>
```
```js
// @ts-nocheck
// #ifdef H5
import * as echarts from 'echarts/dist/echarts.esm.js'
// #endif
const chartRef = ref<LEchartComponentPublicInstance|null>(null);
const init = async () => {
if(chartRef.value== null) return
// #ifdef APP
const chart = await chartRef.value!.init(null)
// #endif
// #ifdef H5
const chart = await chartRef.value!.init(echarts, null)
// #endif
chart.setOption(option)
}
```
## 数据更新
- 1、使用 `ref` 可获取`setOption`设置更新
- 2、也可以拿到图表实例`chart`设置`myChart.setOption(data)`
```js
// ref
this.$refs.chart.setOption(data)
// 图表实例
myChart.setOption(data)
```
## 图表大小
- 在有些场景下,我们希望当容器大小改变时,图表的大小也相应地改变。
```js
// 默认获取容器尺寸
this.$refs.chart.resize()
// 指定尺寸
this.$refs.chart.resize({width: 375, height: 375})
```
## 自定义Tooltips
- uvue\nvue 不支持
由于除H5之外都不存在dom,但又有tooltips个性化的需求,代码就不贴了,看示例吧
```
代码位于/uni_modules/lime-echart/component/lime-echart
```
## 插件标签
- 默认 l-echart 为 component
- 默认 lime-echart 为 demo
```html
// 在任意地方使用可查看domo, 代码位于/uni_modules/lime-echart/component/lime-echart
<lime-echart></lime-echart>
```
## 常见问题
- 钉钉小程序 由于没有`measureText`,模拟的`measureText`又无法得到当前字体的`fontWeight`,故可能存在估计不精细的问题
- 微信小程序 `2d` 只支持 真机调试2.0
- 微信开发工具会出现 `canvas` 不跟随页面的情况,真机不影响
- 微信开发工具会出现 `canvas` 层级过高的问题,真机一般不受影响,可以先测只有两个元素的页面看是否会有层级问题。
- toolbox 不支持 `saveImage`
- echarts 5.3.0 的 lines 不支持 trailLength,故需设置为 `0`
- dataZoom H5不要设置 `showDetail`
- 如果微信小程序的`tooltip`文字有阴影,可能是微信的锅,临时解决方法是`tooltip.shadowBlur = 0`
- 如果钉钉小程序上传时报安全问题`Uint8Clamped`,可以向钉钉反馈是安全代码扫描把Uint8Clamped数组错误识别了,也可以在 echarts 文件修改`Uint8Clamped`
```js
// 找到这段代码把代码中`Uint8Clamped`改成`Uint8_Clamped`,再把下划线去掉,不过直接去掉`Uint8Clamped`也是可行的
// ["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64"],(function(t,e){return t["[object "+e+"Array]"]
// 改成如下
["Int8","Uint8","Uint8_Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64"],(function(t,e){return t["[object "+e.replace('_','')+"Array]"]
```
### vue3
如果您是使用 **vite + vue3** 非微信小程序可能会遇到`echarts`文件缺少`wx`判断导致无法使用或缺少`tooltip`<br>
方式一:可以在`echarts.min.js`文件开头增加以下内容,参考插件内的echart.min.js的做法
```js
let global = null
let wx = uni
```
方式二:在`vite.config.js`的`define`设置环境
```js
// 或者在`vite.config.js`的`define`设置环境
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
const define = {}
if(!["mp-weixin", "h5", "web"].includes(process.env.UNI_PLATFORM)) {
define['global'] = null
define['wx'] = 'uni'
}
export default defineConfig({
plugins: [uni()],
define
});
```
## Props
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------------- | -------- | ------- | ------------ | ----- |
| custom-style | 自定义样式 | `string` | - | - |
| type | 指定 canvas 类型 | `string` | `2d` | |
| is-disable-scroll | 触摸图表时是否禁止页面滚动 | `boolean` | `false` | |
| beforeDelay | 延迟初始化 (毫秒) | `number` | `30` | |
| enableHover | PC端使用鼠标悬浮 | `boolean` | `false` | |
| landscape | 是否旋转90deg,模拟横屏效果 | `boolean` | `false` | |
## 事件
| 参数 | 说明 |
| --------------- | --------------- |
| init(echarts, chart => {}) | 初始化调用函数,第一个参数是传入`echarts`,第二个参数是回调函数,回调函数的参数是 `chart` 实例 |
| setChart(chart => {}) | 已经初始化后,请使用这个方法,是个回调函数,参数是 `chart` 实例 |
| setOption(data) | [图表配置项](https://echarts.apache.org/zh/option.html#title),用于更新 ,传递是数据 `option` |
| clear() | 清空当前实例,会移除实例中所有的组件和图表。 |
| dispose() | 销毁实例 |
| showLoading() | 显示加载 |
| hideLoading() | 隐藏加载 |
| [canvasToTempFilePath](https://uniapp.dcloud.io/api/canvas/canvasToTempFilePath.html#canvastotempfilepath)(opt) | 用于生成图片,与官方使用方法一致,但不需要传`canvasId` |
## 打赏
如果你觉得本插件,解决了你的问题,赠人玫瑰,手留余香。
![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/alipay.png)
![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/wpay.png)
\ No newline at end of file \ No newline at end of file
!function(n,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define([],r):"object"==typeof exports?exports.ecStat=r():n.ecStat=r()}(this,function(){return function(n){function r(e){if(t[e])return t[e].exports;var o=t[e]={exports:{},id:e,loaded:!1};return n[e].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}var t={};return r.m=n,r.c=t,r.p="",r(0)}([function(n,r,t){var e;e=function(n){return{clustering:t(6),regression:t(8),statistics:t(15),histogram:t(7),transform:{regression:t(19),histogram:t(18),clustering:t(17)}}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){return n=null===n?NaN:+n,"number"==typeof n&&!isNaN(n)}function t(n){return isFinite(n)&&n===Math.round(n)}function e(n){if(0===n)return 0;var r=Math.floor(Math.log(n)/Math.LN10);return n/Math.pow(10,r)>=10&&r++,r}return{isNumber:r,isInteger:t,quantityExponent:e}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){for(var r=[];t(n);)r.push(n.length),n=n[0];return r}function t(n){return"[object Array]"===l.call(n)}function e(n,r){for(var t=[],e=0;e<n;e++){t[e]=[];for(var o=0;o<r;o++)t[e][o]=0}return t}function o(n){for(var r=0,t=0;t<n.length;t++)r+=n[t];return r}function i(n,r){for(var t=0,e=0;e<n.length;e++)t+=n[e][r];return t}function a(n,r){return n>r?1:n<r?-1:n===r?0:NaN}function u(n,r,t,e){for(null==t&&(t=0),null==e&&(e=n.length);t<e;){var o=Math.floor((t+e)/2),i=a(n[o],r);if(i>0)e=o;else{if(!(i<0))return o+1;t=o+1}}return t}function s(n,r,t){if(n&&r){if(n.map&&n.map===c)return n.map(r,t);for(var e=[],o=0,i=n.length;o<i;o++)e.push(r.call(t,n[o],o,n));return e}}var l=Object.prototype.toString,f=Array.prototype,c=f.map;return{size:r,isArray:t,zeros:e,sum:o,sumOfColumn:i,ascending:a,bisect:u,map:s}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n,r){return"number"==typeof n?[n]:null==n?r:n}function e(n,r){function t(n){return!e||o.hasOwnProperty(n)}r=r||{};var e=r.dimensions,o={};if(null!=e)for(var i=0;i<e.length;i++)o[e[i]]=!0;var s=r.toOneDimensionArray?e?e[0]:0:null;if(!a(n))throw new Error("Invalid data type, you should input an array");var f=[],c=u(n);if(1===c.length)for(var i=0;i<c[0];i++){var v=n[i];l(v)&&f.push(v)}else if(2===c.length)for(var i=0;i<c[0];i++){for(var h=!0,v=n[i],p=0;p<c[1];p++)t(p)&&!l(v[p])&&(h=!1);h&&f.push(null!=s?v[s]:v)}return f}function o(n){var r=n.toString(),t=r.indexOf(".");return t<0?0:r.length-1-t}var i=t(2),a=i.isArray,u=i.size,s=t(1),l=s.isNumber;return{normalizeDimensions:r,dataPreprocess:e,getPrecision:o}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){return function(n,r){var t=n.length;if(!t)return 0;if(r<=0||t<2)return n[0];if(r>=1)return n[t-1];var e=(t-1)*r,o=Math.floor(e),i=n[o],a=n[o+1];return i+(a-i)*(e-o)}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n,r){function t(n,r){if(!n)throw new Error("Can not find dimension by "+r)}if(null!=r){var e=n.upstream;if(o.isArray(r)){for(var i=[],a=0;a<r.length;a++){var u=e.getDimensionInfo(r[a]);t(u,r[a]),i[a]=u.index}return i}var u=e.getDimensionInfo(r);return t(u,r),u.index}}function e(n){function r(n){if(i.isNumber(n))return{index:n};if(a.isObject(n)&&i.isNumber(n.index))return n;throw new Error("Illegle new dimensions config. Expect `{ name: string, index: number }`.")}if(o.isArray(n)){for(var t=[],e=[],u=0;u<n.length;u++){var s=r(n[u]);t.push(s.name),e.push(s.index)}return{name:t,index:e}}if(null!=n)return r(n)}var o=t(2),i=t(1),a=t(20);return{normalizeExistingDimensions:r,normalizeNewDimensions:e}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n,r,t){for(var o,i,s,f,c=x(n.length,2),v=a(r,l(n,t.dimensions)),h=!0;h;){h=!1;for(var p=0;p<n.length;p++){o=1/0,i=-1;for(var d=0;d<r;d++)s=u(n[p],v[d],t),s<o&&(o=s,i=d);c[p][0]!==i&&(h=!0),c[p][0]=i,c[p][1]=o}for(var p=0;p<r;p++){f=[];for(var d=0;d<c.length;d++)c[d][0]===p&&f.push(n[d]);v[p]=e(f,t)}}var m={centroids:v,clusterAssigned:c};return m}function e(n,r){for(var t,e,o=[],i=0;i<r.dimensions.length;i++){var a=r.dimensions[i];t=0;for(var u=0;u<n.length;u++)t+=n[u][a];e=t/n.length,o.push(e)}return o}function o(n,t,o){function a(n,r){N[n][1]=r}function l(n){return N[n][1]}function f(){if(F<h){S=1/0;for(var n,t,e,o=0;o<O.length;o++){q=[],P=[];for(var i=0;i<E.length;i++)y(i)===o?q.push(E[i]):P.push(l(i));L=r(q,2,b),T=m(L.clusterAssigned,1),j=g(P),T+j<S&&(S=j+T,n=o,t=L.centroids,e=L.clusterAssigned)}for(var i=0;i<e.length;i++)0===e[i][0]?e[i][0]=n:1===e[i][0]&&(e[i][0]=O.length);O[n]=t[0],O.push(t[1]);for(var i=0,o=0;i<E.length&&o<e.length;i++)y(i)===n&&(d(i,e[o][0]),a(i,e[o++][1]));var u=[];if(!D){for(var i=0;i<O.length;i++){u[i]=[];for(var o=0;o<E.length;o++)y(o)===i&&u[i].push(E[o])}V.pointsInCluster=u}F++}else V.isEnd=!0}var v=(M(t)?{clusterCount:t,stepByStep:o}:t)||{clusterCount:2},h=v.clusterCount;if(!(h<2)){var p,d,y,b=s(n,v),D=b.outputType===w.SINGLE,E=c(n,{dimensions:b.dimensions}),N=x(E.length,2);if(D){p=[];var C=b.outputClusterIndexDimension;d=function(n,r){p[n][C]=r},y=function(n){return p[n][C]};for(var I=0;I<E.length;I++)p.push(E[I].slice()),a(I,0),d(I,0)}else d=function(n,r){N[n][0]=r},y=function(n){return N[n][0]};for(var A=e(E,b),O=[A],I=0;I<E.length;I++){var z=u(E[I],A,b);a(I,z)}var S,q,P,L,T,j,F=1,V={data:p,centroids:O,isEnd:!1};if(D||(V.clusterAssment=N),v.stepByStep)V.next=function(){return f(),i(V,b),V};else for(;f(),!V.isEnd;);return i(V,b),V}}function i(n,r){var t=r.outputCentroidDimensions;if(r.outputType===w.SINGLE&&null!=t)for(var e=n.data,o=n.centroids,i=0;i<e.length;i++)for(var a=e[i],u=a[r.outputClusterIndexDimension],s=o[u],l=Math.min(s.length,t.length),f=0;f<l;f++)a[t[f]]=s[f]}function a(n,r){for(var t=x(n,r.length),e=0;e<r.length;e++)for(var o=r[e],i=0;i<n;i++)t[i][e]=o.min+o.span*Math.random();return t}function u(n,r,t){for(var e=0,o=t.dimensions,i=t.rawExtents,a=0;a<o.length;a++){var u=i[a].span;if(u){var s=o[a],l=(n[s]-r[a])/u;e+=y(l,2)}}return e}function s(n,r){var t=d(n);if(t.length<1)throw new Error("The input data of clustering should be two-dimension array.");for(var e=t[1],o=[],i=0;i<e;i++)o.push(i);var a=v(r.dimensions,o),u=r.outputType||w.MULTIPLE,s=r.outputClusterIndexDimension;if(u===w.SINGLE&&!p.isNumber(s))throw new Error("outputClusterIndexDimension is required as a number.");var f=l(n,a);return{dimensions:a,rawExtents:f,outputType:u,outputClusterIndexDimension:s,outputCentroidDimensions:r.outputCentroidDimensions}}function l(n,r){for(var t=[],e=r.length,o=0;o<e;o++)t.push({min:1/0,max:-(1/0)});for(var o=0;o<n.length;o++)for(var i=n[o],a=0;a<e;a++){var u=t[a],s=i[r[a]];u.min>s&&(u.min=s),u.max<s&&(u.max=s)}for(var o=0;o<e;o++)t[o].span=t[o].max-t[o].min;return t}var f=t(3),c=f.dataPreprocess,v=f.normalizeDimensions,h=t(2),p=t(1),d=h.size,m=h.sumOfColumn,g=h.sum,x=h.zeros,p=t(1),M=p.isNumber,y=Math.pow,w={SINGLE:"single",MULTIPLE:"multiple"};return{OutputType:w,hierarchicalKMeans:o}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n,r){for(var t="string"==typeof r?{method:r}:r||{},i=null==t.method?m.squareRoot:m[t.method],a=l(t.dimensions),u=s(n,{dimensions:a,toOneDimensionArray:!0}),f=e(u),c=o(u),g=i(u,c,f),x=d(c,f,g),M=x.step,y=x.toFixedPrecision,w=h(+(Math.ceil(c/M)*M).toFixed(y),+(Math.floor(f/M)*M).toFixed(y),M,y),b=w.length,D=new Array(b+1),E=0;E<=b;E++)D[E]={},D[E].sample=[],D[E].x0=E>0?w[E-1]:w[E]-c===M?c:w[E]-M,D[E].x1=E<b?w[E]:f-w[E-1]===M?f:w[E-1]+M;for(var E=0;E<u.length;E++)c<=u[E]&&u[E]<=f&&D[p(w,u[E],0,b)].sample.push(u[E]);var n=v(D,function(n){return[+((n.x0+n.x1)/2).toFixed(y),n.sample.length,n.x0,n.x1,n.x0+" - "+n.x1]}),N=v(D,function(n){return[n.x0,n.x1,n.sample.length]});return{bins:D,data:n,customData:N}}var e=t(10),o=t(12),i=t(4),a=t(9),u=t(3),s=u.dataPreprocess,l=u.normalizeDimensions,f=t(2),c=f.ascending,v=f.map,h=t(21),p=f.bisect,d=t(22),m={squareRoot:function(n){var r=Math.ceil(Math.sqrt(n.length));return r>50?50:r},scott:function(n,r,t){return Math.ceil((t-r)/(3.5*a(n)*Math.pow(n.length,-1/3)))},freedmanDiaconis:function(n,r,t){return n.sort(c),Math.ceil((t-r)/(2*(i(n,.75)-i(n,.25))*Math.pow(n.length,-1/3)))},sturges:function(n){return Math.ceil(Math.log(n.length)/Math.LN2)+1}};return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n,r){for(var t=0;t<n.length-1;t++){for(var e=t,o=t+1;o<n.length-1;o++)Math.abs(n[t][o])>Math.abs(n[t][e])&&(e=o);for(var i=t;i<n.length;i++){var a=n[i][t];n[i][t]=n[i][e],n[i][e]=a}for(var u=t+1;u<n.length-1;u++)for(var s=n.length-1;s>=t;s--)n[s][u]-=n[s][t]/n[t][t]*n[t][u]}for(var l=new Array(r),f=n.length-1,o=n.length-2;o>=0;o--){for(var a=0,t=o+1;t<n.length-1;t++)a+=n[t][o]*l[t];l[o]=(n[f][o]-a)/n[o][o]}return l}var e=t(3),o=e.dataPreprocess,i=e.normalizeDimensions,a={linear:function(n,r){for(var t=r.dimensions[0],e=r.dimensions[1],o=0,i=0,a=0,u=0,s=n.length,l=0;l<s;l++){var f=n[l];o+=f[t],i+=f[e],a+=f[t]*f[e],u+=f[t]*f[t]}for(var c=(s*a-o*i)/(s*u-o*o),v=i/s-c*o/s,h=[],p=0;p<n.length;p++){var f=n[p],d=f.slice();d[t]=f[t],d[e]=c*f[t]+v,h.push(d)}var m="y = "+Math.round(100*c)/100+"x + "+Math.round(100*v)/100;return{points:h,parameter:{gradient:c,intercept:v},expression:m}},linearThroughOrigin:function(n,r){for(var t=r.dimensions[0],e=r.dimensions[1],o=0,i=0,a=0;a<n.length;a++){var u=n[a];o+=u[t]*u[t],i+=u[t]*u[e]}for(var s=i/o,l=[],f=0;f<n.length;f++){var u=n[f],c=u.slice();c[t]=u[t],c[e]=u[t]*s,l.push(c)}var v="y = "+Math.round(100*s)/100+"x";return{points:l,parameter:{gradient:s},expression:v}},exponential:function(n,r){for(var t=r.dimensions[0],e=r.dimensions[1],o=0,i=0,a=0,u=0,s=0,l=0,f=0;f<n.length;f++){var c=n[f];o+=c[t],i+=c[e],l+=c[t]*c[e],a+=c[t]*c[t]*c[e],u+=c[e]*Math.log(c[e]),s+=c[t]*c[e]*Math.log(c[e])}for(var v=i*a-l*l,h=Math.pow(Math.E,(a*u-l*s)/v),p=(i*s-l*u)/v,d=[],m=0;m<n.length;m++){var c=n[m],g=c.slice();g[t]=c[t],g[e]=h*Math.pow(Math.E,p*c[t]),d.push(g)}var x="y = "+Math.round(100*h)/100+"e^("+Math.round(100*p)/100+"x)";return{points:d,parameter:{coefficient:h,index:p},expression:x}},logarithmic:function(n,r){for(var t=r.dimensions[0],e=r.dimensions[1],o=0,i=0,a=0,u=0,s=0;s<n.length;s++){var l=n[s];o+=Math.log(l[t]),i+=l[e]*Math.log(l[t]),a+=l[e],u+=Math.pow(Math.log(l[t]),2)}for(var f=(s*i-a*o)/(s*u-o*o),c=(a-f*o)/s,v=[],h=0;h<n.length;h++){var l=n[h],p=l.slice();p[t]=l[t],p[e]=f*Math.log(l[t])+c,v.push(p)}var d="y = "+Math.round(100*c)/100+" + "+Math.round(100*f)/100+"ln(x)";return{points:v,parameter:{gradient:f,intercept:c},expression:d}},polynomial:function(n,t){var e=t.dimensions[0],o=t.dimensions[1],i=t.order;null==i&&(i=2);for(var a=[],u=[],s=i+1,l=0;l<s;l++){for(var f=0,c=0;c<n.length;c++){var v=n[c];f+=v[o]*Math.pow(v[e],l)}u.push(f);for(var h=[],p=0;p<s;p++){for(var d=0,m=0;m<n.length;m++)d+=Math.pow(n[m][e],l+p);h.push(d)}a.push(h)}a.push(u);for(var g=r(a,s),x=[],l=0;l<n.length;l++){for(var M=0,v=n[l],c=0;c<g.length;c++)M+=g[c]*Math.pow(v[e],c);var y=v.slice();y[e]=v[e],y[o]=M,x.push(y)}for(var w="y = ",l=g.length-1;l>=0;l--)w+=l>1?Math.round(g[l]*Math.pow(10,l+1))/Math.pow(10,l+1)+"x^"+l+" + ":1===l?Math.round(100*g[l])/100+"x + ":Math.round(100*g[l])/100;return{points:x,parameter:g,expression:w}}},u=function(n,r,t){var e="number"==typeof t?{order:t}:t||{},u=i(e.dimensions,[0,1]),s=o(r,{dimensions:u}),l=a[n](s,{order:e.order,dimensions:u}),f=u[0];return l.points.sort(function(n,r){return n[f]-r[f]}),l};return u}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r=t(13);return function(n){var t=r(n);return t?Math.sqrt(t):t}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){for(var r=-(1/0),t=0;t<n.length;t++)o(n[t])&&n[t]>r&&(r=n[t]);return r}var e=t(1),o=e.isNumber;return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){var r=n.length;return r?e(n)/n.length:0}var e=t(14);return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){for(var r=1/0,t=0;t<n.length;t++)o(n[t])&&n[t]<r&&(r=n[t]);return r}var e=t(1),o=e.isNumber;return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){var r=n.length;if(!r||r<2)return 0;if(n.length>=2){for(var t,e=i(n),a=0,u=0;u<n.length;u++)o(n[u])&&(t=n[u]-e,a+=t*t);return a/(n.length-1)}}var e=t(1),o=e.isNumber,i=t(11);return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){var r=n.length;if(!r)return 0;for(var t=0,e=0;e<r;e++)o(n[e])&&(t+=n[e]);return t}var e=t(1),o=e.isNumber;return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r={};return r.max=t(10),r.deviation=t(9),r.mean=t(11),r.median=t(16),r.min=t(12),r.quantile=t(4),r.sampleVariance=t(13),r.sum=t(14),r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n){return e(n,.5)}var e=t(4);return r}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r=t(6),e=t(1),o=t(5),i=e.isNumber;return{type:"ecStat:clustering",transform:function(n){var t=n.upstream,e=n.config||{},a=e.clusterCount;if(!i(a)||a<=0)throw new Error('config param "clusterCount" need to be specified as an interger greater than 1.');if(1===a)return[{},{data:[]}];var u=o.normalizeNewDimensions(e.outputClusterIndexDimension),s=o.normalizeNewDimensions(e.outputCentroidDimensions);if(null==u)throw new Error("outputClusterIndexDimension is required as a number.");for(var l=r.hierarchicalKMeans(t.cloneRawData(),{clusterCount:a,stepByStep:!1,dimensions:o.normalizeExistingDimensions(n,e.dimensions),outputType:r.OutputType.SINGLE,outputClusterIndexDimension:u.index,outputCentroidDimensions:(s||{}).index}),f=t.cloneAllDimensionInfo(),c=[],v=0;v<f.length;v++){var h=f[v];c.push(h.name)}if(c[u.index]=u.name,s)for(var v=0;v<s.index.length;v++)null!=s.name[v]&&(c[s.index[v]]=s.name[v]);return[{dimensions:c,data:l.data},{data:l.centroids}]}}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r=t(7),e=t(5);return{type:"ecStat:histogram",transform:function(n){var t=n.upstream,o=n.config||{},i=r(t.cloneRawData(),{method:o.method,dimensions:e.normalizeExistingDimensions(n,o.dimensions)});return[{dimensions:["MeanOfV0V1","VCount","V0","V1","DisplayableName"],data:i.data},{data:i.customData}]}}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r=t(8),e=t(5),o=2;return{type:"ecStat:regression",transform:function(n){var t=n.upstream,i=n.config||{},a=i.method||"linear",u=r(a,t.cloneRawData(),{order:i.order,dimensions:e.normalizeExistingDimensions(n,i.dimensions)}),s=u.points,l=i.formulaOn;null==l&&(l="end");var f;if("none"!==l){for(var c=0;c<s.length;c++)s[c][o]="start"===l&&0===c||"all"===l||"end"===l&&c===s.length-1?u.expression:"";f=t.cloneAllDimensionInfo(),f[o]={}}return[{dimensions:f,data:s}]}}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){function r(n,r){if(Object.assign)Object.assign(n,r);else for(var t in r)r.hasOwnProperty(t)&&(n[t]=r[t]);return n}function t(n){const r=typeof n;return"function"===r||!!n&&"object"===r}return{extend:r,isObject:t}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r=t(3),e=r.getPrecision;return function(n,r,t,o){var i=arguments.length;i<2?(r=n,n=0,t=1):i<3?t=1:i<4?(t=+t,o=e(t)):o=+o;for(var a=Math.ceil(((r-n)/t).toFixed(o)),u=new Array(a+1),s=0;s<a+1;s++)u[s]=+(n+s*t).toFixed(o);return u}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))},function(n,r,t){var e;e=function(n){var r=t(1);return function(n,t,e){var o=Math.abs(t-n)/e,i=r.quantityExponent(o),a=Math.pow(10,i),u=o/a;u>=Math.sqrt(50)?a*=10:u>=Math.sqrt(10)?a*=5:u>=Math.sqrt(2)&&(a*=2);var s=i<0?-i:0,l=+(t>=n?a:-a).toFixed(s);return{step:l,toFixedPrecision:s}}}.call(r,t,r,n),!(void 0!==e&&(n.exports=e))}])});
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function i(e,i){return n.call(e,i)}var t=[];function o(){return window.__dcloud_weex_postMessage||window.__dcloud_weex_}function a(){return window.__uniapp_x_postMessage||window.__uniapp_x_}var r=function(e,n){var i={options:{timestamp:+new Date},name:e,arg:n};if(a()){if("postMessage"===e){var r={data:n};return window.__uniapp_x_postMessage?window.__uniapp_x_postMessage(r):window.__uniapp_x_.postMessage(JSON.stringify(r))}var d={type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}};window.__uniapp_x_postMessage?window.__uniapp_x_postMessageToService(d):window.__uniapp_x_.postMessageToService(JSON.stringify(d))}else if(o()){if("postMessage"===e){var s={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(s):window.__dcloud_weex_.postMessage(JSON.stringify(s))}var w={type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(w):window.__dcloud_weex_.postMessageToService(JSON.stringify(w))}else{if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:i,pageId:""},"*");if(0===t.length){var u=plus.webview.currentWebview();if(!u)throw new Error("plus.webview.currentWebview() is undefined");var g=u.parent(),v="";v=g?g.id:u.id,t.push(v)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}},"__uniapp__service");else{var c=JSON.stringify(i);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(c,",").concat(JSON.stringify(t),");"))}}},d={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;r("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("redirectTo",{url:encodeURI(n)})},getEnv:function(e){a()?e({uvue:!0}):o()?e({nvue:!0}):window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};r("postMessage",e.data||{})}},s=/uni-app/i.test(navigator.userAgent),w=/Html5Plus/i.test(navigator.userAgent),u=/complete|loaded|interactive/;var g=window.my&&navigator.userAgent.indexOf(["t","n","e","i","l","C","y","a","p","i","l","A"].reverse().join(""))>-1;var v=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var c=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var _=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var m=window.qa&&/quickapp/i.test(navigator.userAgent);var f=window.ks&&window.ks.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var l=window.tt&&window.tt.miniProgram&&/Lark|Feishu/i.test(navigator.userAgent);var E=window.jd&&window.jd.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var x=window.xhs&&window.xhs.miniProgram&&/xhsminiapp/i.test(navigator.userAgent);for(var S,h=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},y=[function(e){if(s||w)return window.__uniapp_x_postMessage||window.__uniapp_x_||window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&u.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),d},function(e){if(_)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(c)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(g){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(v)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(p)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(m){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(f)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.ks.miniProgram},function(e){if(l)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(E)return window.JDJSBridgeReady&&window.JDJSBridgeReady.invoke?setTimeout(e,0):document.addEventListener("JDJSBridgeReady",e),window.jd.miniProgram},function(e){if(x)return window.xhs.miniProgram},function(e){return document.addEventListener("DOMContentLoaded",e),d}],M=0;M<y.length&&!(S=y[M](h));M++);S||(S={});var P="undefined"!=typeof uni?uni:{};if(!P.navigateTo)for(var b in S)i(S,b)&&(P[b]=S[b]);return P.webView=S,P}));
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style type="text/css">
html,
body,
.canvas {
padding: 0;
margin: 0;
overflow-y: hidden;
background-color: transparent;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="canvas" id="limeChart"></div>
<script type="text/javascript" src="./uni.webview.1.5.5.js"></script>
<script type="text/javascript" src="./echarts.min.js"></script>
<script type="text/javascript" src="./ecStat.min.js"></script>
<!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-liquidfill@latest/dist/echarts-liquidfill.min.js"></script> -->
<script>
let chart = null;
let cache = [];
console.log = function() {
emit('log', {
log: arguments,
})
}
function emit(event, data) {
postMessage({
event,
data
})
cache = []
}
function postMessage(data) {
uni.webView.postMessage({
data
})
// window.__uniapp_x_.postMessage(JSON.stringify(data))
};
function stringify(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
}
function parse(name, callback, options) {
const optionNameReg = /[\w]+\.setOption\(([\w]+\.)?([\w]+)\)/
if (optionNameReg.test(callback)) {
const optionNames = callback.match(optionNameReg)
if (optionNames[1]) {
const _this = optionNames[1].split('.')[0]
window[_this] = {}
window[_this][optionNames[2]] = options
return optionNames[2]
} else {
return null
}
}
return null
}
function init(callback, options, opts, theme) {
if (!chart) {
chart = echarts.init(document.getElementById('limeChart'), theme, opts)
if (options) {
chart.setOption(options)
}
}
}
function on(data) {
if (chart && data.length > 0) {
const [type, query] = data
const key = `${type}${JSON.stringify(query||'')}`
if (query) {
chart.on(type, query, function(options) {
var obj = {};
Object.keys(options).forEach(function(key) {
if (key != 'event') {
obj[key] = options[key];
}
});
emit(key, {
event: key,
options: obj,
});
});
} else {
chart.on(type, function(options) {
var obj = {};
Object.keys(options).forEach(function(key) {
if (key != 'event') {
obj[key] = options[key];
}
});
emit(key, {
event: key,
options: obj,
});
});
}
}
}
function setChart(callback, options) {
if (!callback) return
if (chart && callback && options) {
var r = null
const name = parse('r', callback, options)
if (name) this[name] = options
eval(`r = ${callback};`)
if (r) {
r(chart)
}
}
}
function setOption(data) {
if (chart) chart.setOption(data[0], data[1])
}
function showLoading(data) {
if (chart) chart.showLoading(data[0], data[1])
}
function hideLoading() {
if (chart) chart.hideLoading()
}
function clear() {
if (chart) chart.clear()
}
function dispose() {
if (chart) chart.dispose()
}
function resize(size) {
if (chart) chart.resize(size)
}
function canvasToTempFilePath(opt) {
if (chart) {
delete opt.success
const src = chart.getDataURL(opt)
postMessage({
// event: 'file',
file: src
})
}
}
document.addEventListener('touchmove', () => {
})
</script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
## 1.3.7(2024-05-10)
1. 修复添加超链接后,不触发input更新当前最新内容的bug
## 1.3.6(2024-05-09)
1. 文档迁移
## 1.3.5(2024-05-09)
1. 所有事件携带编辑器id参数,以便循环时能区分处理
2. 更新示例工程
## 1.3.4(2024-05-08)
1. 更新示例工程
2. 新增editorId参数
## 1.3.3(2024-03-22)
1. 修复微信小程序长按无法粘贴的问题
## 1.3.2(2024-03-14)
1. 更新了toolbar样式与配置,见文档
2. 更新示例工程,媒体查询响应式写法
3. 优化了只读模式效果,开启只读模式后,文章内容的超链接可正常点击并跳转
## 1.3.1(2024-03-14)
1. 优化了只读功能,开启只读后自动隐藏工具栏
2. 更新示例工程
## 1.3.0(2024-03-07)
1. 新增addLink的emit事件
## 1.2.9(2024-02-23)
1. 更新文档
## 1.2.8(2024-02-23)
1. 新增了添加超链接的工具,toolbar中link字段,默认开启
2. 优化了部分逻辑
3. 更新文档、更新示例工程
## 1.2.7(2024-02-23)
1. 更新文档,更新示例工程
2. 添加toolbar中图标字体大小可配置项
## 1.2.6(2024-02-22)
1. 添加导出工具按钮,可将当前已编辑的html导出至页面解析
2. 超链接工具按钮正在尝试开发中(貌似目前官方不支持)
## 1.2.5(2024-02-19)
1. 更新示例工程(吸顶写法)
2. 完善调色板功能
## 1.2.4(2024-02-18)
1. 修复工具栏颜色按钮底色动态切换问题
## 1.2.3(2024-02-18)
1. 更新示例工程
## 1.2.2(2024-02-18)
1. 删除log调试打印
## 1.2.1(2024-02-18)
1. 修复了颜色图标不会动态切换的问题
## 1.2.0(2024-02-18)
1. 修复选择颜色时会将所选文字删除的bug
## 1.1.9(2024-02-04)
1. 更新示例工程
## 1.1.8(2024-02-04)
1. 文档修改
## 1.1.7(2024-02-04)
1. 新增toolbar配置项,可自由配置工具栏工具列表
2. 移除组件内原templates属性,默认初始化编辑器内容请看文档使用方式示例
3. 更新文档
## 1.1.6(2024-01-31)
1. 更好的兼容vue2了,修复在vue2下高度可能超出的问题
2. 示例工程兼容vue2
## 1.1.5(2024-01-30)
1. 修复工具栏字体按钮无效的问题
## 1.1.4(2024-01-30)
1. 解决默认初始化内容时前缀空格或缩进无效的问题
2. 解决点击工具栏高亮状态后输入内容时便失去高亮的bug
3. 更新示例工程
## 1.1.3(2024-01-23)
1. 重写高度动态计算逻辑,现在对不同屏幕尺寸的适应性更强了
## 1.1.2(2024-01-17)
1. 修复分割线会生成多条的问题
## 1.1.1(2024-01-15)
1. 更新文档
## 1.1.0(2024-01-15)
1. insertText方法在插入内容的时候会移动光标聚焦,导致焦点回滚到视口处
2. 更新示例工程
## 1.0.9(2024-01-04)
1. 更新文档
## 1.0.8(2024-01-04)
1. 修复h5端官方cdn请求失败的问题,详见问答贴:https://ask.dcloud.net.cn/article/40900
## 1.0.7(2024-01-03)
1. 移除v-bind="$attrs",该写法在微信小程序不支持
## 1.0.6(2023-12-29)
1. 更新文档
## 1.0.5(2023-12-29)
1. 更新了init方法,可以使用返回的editor实例尽情自定义
2. 组件在<editor>上添加v-bind="$attrs"属性穿透,可以使用原editor参数,官方文档:https://uniapp.dcloud.net.cn/component/editor.html
## 1.0.4(2023-12-29)
1. 优化了切换文字和背景颜色是,可能会导致切换后不生效的问题
2. 修复在部分设备上的微信小程序中可能会存在颜色版无法正常滑动的问题
3. 更友好的交互体验:添加图标悬停字样描述、添加格式化文本弹窗确认
4. 有插入视频的需求,暂时可能无法实现,官方给予的回复是:目前各端的eidtor组件都不能直接插入视频,编辑时可以采用视频封面占位,并在图片中保存视频信息,在预览时再还原为视频。
## 1.0.3(2023-10-13)
1. 更新readme文档
2. 更新调整组件示例项目,添加插件代码中部分注释
## 1.0.2(2023-10-13)
1. 更新uni_modules规范,可一键导入组件
2. 更新组件示例项目(包括使用uniCloud.uploadFile多选上传图片示例方法)
## 1.0.1(2023-10-12)
1. 修复小程序中自动聚焦滚动到富文本组件区域的bug
2. 略微调整了富文本上方toolbar工具栏中按钮的大小尺寸
## 1.0.0(2023-9-19)
1. 新增字体与背景颜色板
2. 可自定义预设内容模板
3. 解决官方样例在小程序和app部分报错不兼容的问题
4. 可配合云存储上传富文本中插入的图片 本质上是基于官方内置富文本editor组件改版封装,所以官方有的功能都有,官方能兼容的也都兼容
<template>
<view v-if="show" class="t-wrapper" @touchmove.stop.prevent="moveHandle">
<view class="t-mask" :class="{ active: active }" @click.stop="close"></view>
<view class="t-box" :class="{ active: active }">
<view class="t-header">
<view class="t-header-button" @click="close">取消</view>
<view class="t-header-button" @click="confirm">确认</view>
</view>
<view class="t-color__box" :style="{ background: 'rgb(' + bgcolor.r + ',' + bgcolor.g + ',' + bgcolor.b + ')' }">
<view
class="t-background boxs"
@touchstart="touchstart($event, 0)"
@touchmove="touchmove($event, 0)"
@touchend="touchend($event, 0)"
>
<view class="t-color-mask"></view>
<view class="t-pointer" :style="{ top: site[0].top - 8 + 'px', left: site[0].left - 8 + 'px' }"></view>
</view>
</view>
<view class="t-control__box">
<view class="t-control__color">
<view
class="t-control__color-content"
:style="{ background: 'rgba(' + rgba.r + ',' + rgba.g + ',' + rgba.b + ',' + rgba.a + ')' }"
></view>
</view>
<view class="t-control-box__item">
<view
class="t-controller boxs"
@touchstart="touchstart($event, 1)"
@touchmove="touchmove($event, 1)"
@touchend="touchend($event, 1)"
>
<view class="t-hue">
<view class="t-circle" :style="{ left: site[1].left - 12 + 'px' }"></view>
</view>
</view>
<view
class="t-controller boxs"
@touchstart="touchstart($event, 2)"
@touchmove="touchmove($event, 2)"
@touchend="touchend($event, 2)"
>
<view class="t-transparency">
<view class="t-circle" :style="{ left: site[2].left - 12 + 'px' }"></view>
</view>
</view>
</view>
</view>
<view class="t-result__box">
<view v-if="mode" class="t-result__item">
<view class="t-result__box-input">{{ hex }}</view>
<view class="t-result__box-text">HEX</view>
</view>
<template v-else>
<view class="t-result__item">
<view class="t-result__box-input">{{ rgba.r }}</view>
<view class="t-result__box-text">R</view>
</view>
<view class="t-result__item">
<view class="t-result__box-input">{{ rgba.g }}</view>
<view class="t-result__box-text">G</view>
</view>
<view class="t-result__item">
<view class="t-result__box-input">{{ rgba.b }}</view>
<view class="t-result__box-text">B</view>
</view>
<view class="t-result__item">
<view class="t-result__box-input">{{ rgba.a }}</view>
<view class="t-result__box-text">A</view>
</view>
</template>
<view class="t-result__item t-select" @click="select">
<view class="t-result__box-input">
<view>切换</view>
<view>模式</view>
</view>
</view>
</view>
<view class="t-alternative">
<view class="t-alternative__item" v-for="(item, index) in colorList" :key="index">
<view
class="t-alternative__item-content"
:style="{ background: 'rgba(' + item.r + ',' + item.g + ',' + item.b + ',' + item.a + ')' }"
@click="selectColor(item)"
></view>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
props: {
color: {
type: Object,
default: () => {
return {
r: 0,
g: 0,
b: 0,
a: 0
}
}
},
spareColor: {
type: Array,
default() {
return []
}
}
},
data() {
return {
show: false,
active: false,
// rgba 颜色
rgba: {
r: 0,
g: 0,
b: 0,
a: 1
},
// hsb 颜色
hsb: {
h: 0,
s: 0,
b: 0
},
site: [
{
top: 0,
left: 0
},
{
left: 0
},
{
left: 0
}
],
index: 0,
bgcolor: {
r: 255,
g: 0,
b: 0,
a: 1
},
hex: '#000000',
mode: true,
colorList: [
{
r: 244,
g: 67,
b: 54,
a: 1
},
{
r: 233,
g: 30,
b: 99,
a: 1
},
{
r: 156,
g: 39,
b: 176,
a: 1
},
{
r: 103,
g: 58,
b: 183,
a: 1
},
{
r: 63,
g: 81,
b: 181,
a: 1
},
{
r: 33,
g: 150,
b: 243,
a: 1
},
{
r: 3,
g: 169,
b: 244,
a: 1
},
{
r: 0,
g: 188,
b: 212,
a: 1
},
{
r: 0,
g: 150,
b: 136,
a: 1
},
{
r: 76,
g: 175,
b: 80,
a: 1
},
{
r: 139,
g: 195,
b: 74,
a: 1
},
{
r: 205,
g: 220,
b: 57,
a: 1
},
{
r: 255,
g: 235,
b: 59,
a: 1
},
{
r: 255,
g: 193,
b: 7,
a: 1
},
{
r: 255,
g: 152,
b: 0,
a: 1
},
{
r: 255,
g: 87,
b: 34,
a: 1
},
{
r: 121,
g: 85,
b: 72,
a: 1
},
{
r: 158,
g: 158,
b: 158,
a: 1
},
{
r: 0,
g: 0,
b: 0,
a: 0.5
},
{
r: 0,
g: 0,
b: 0,
a: 0
}
]
}
},
created() {
this.ready()
},
methods: {
ready() {
this.rgba = this.color
if (this.spareColor.length !== 0) {
this.colorList = this.spareColor
}
},
/**
* 初始化
*/
init() {
// hsb 颜色
this.hsb = this.rgbToHex(this.rgba)
// this.setColor();
this.setValue(this.rgba)
},
moveHandle() {},
open() {
this.show = true
this.$nextTick(() => {
this.init()
setTimeout(() => {
this.active = true
setTimeout(() => {
this.getSelectorQuery()
}, 350)
}, 50)
})
},
close() {
this.active = false
this.$nextTick(() => {
setTimeout(() => {
this.show = false
}, 500)
})
},
confirm() {
this.close()
this.$emit('confirm', {
rgba: this.rgba,
hex: this.hex
})
},
// 选择模式
select() {
this.mode = !this.mode
},
// 常用颜色选择
selectColor(item) {
this.setColorBySelect(item)
},
touchstart(e, index) {
const { pageX, pageY, clientX, clientY } = e.touches[0]
// 部分机型可能没有pageX或clientX,因此此处需要做兼容
this.moveX = pageX || clientX
this.moveY = pageY || clientY
this.setPosition(this.moveX, this.moveY, index)
},
touchmove(e, index) {
const { pageX, pageY, clientX, clientY } = e.touches[0]
this.moveX = pageX || clientX
this.moveY = pageY || clientY
this.setPosition(this.moveX, this.moveY, index)
},
touchend(e, index) {},
/**
* 设置位置
*/
setPosition(x, y, index) {
this.index = index
const { top, left, width, height } = this.position[index]
// 设置最大最小值
this.site[index].left = Math.max(0, Math.min(parseInt(x - left), width))
if (index === 0) {
this.site[index].top = Math.max(0, Math.min(parseInt(y - top), height))
// 设置颜色
this.hsb.s = parseInt((100 * this.site[index].left) / width)
this.hsb.b = parseInt(100 - (100 * this.site[index].top) / height)
this.setColor()
this.setValue(this.rgba)
} else {
this.setControl(index, this.site[index].left)
}
},
/**
* 设置 rgb 颜色
*/
setColor() {
const rgb = this.HSBToRGB(this.hsb)
this.rgba.r = rgb.r
this.rgba.g = rgb.g
this.rgba.b = rgb.b
},
/**
* 设置二进制颜色
* @param {Object} rgb
*/
setValue(rgb) {
this.hex = '#' + this.rgbToHex(rgb)
},
setControl(index, x) {
const { top, left, width, height } = this.position[index]
if (index === 1) {
this.hsb.h = parseInt((360 * x) / width)
this.bgcolor = this.HSBToRGB({
h: this.hsb.h,
s: 100,
b: 100
})
this.setColor()
} else {
this.rgba.a = (x / width).toFixed(1)
}
this.setValue(this.rgba)
},
/**
* rgb 转 二进制 hex
* @param {Object} rgb
*/
rgbToHex(rgb) {
let hex = [rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16)]
hex.map(function (str, i) {
if (str.length == 1) {
hex[i] = '0' + str
}
})
return hex.join('')
},
setColorBySelect(getrgb) {
const { r, g, b, a } = getrgb
let rgb = {}
rgb = {
r: r ? parseInt(r) : 0,
g: g ? parseInt(g) : 0,
b: b ? parseInt(b) : 0,
a: a ? a : 0
}
this.rgba = rgb
this.hsb = this.rgbToHsb(rgb)
this.changeViewByHsb()
},
changeViewByHsb() {
const [a, b, c] = this.position
this.site[0].left = parseInt((this.hsb.s * a.width) / 100)
this.site[0].top = parseInt(((100 - this.hsb.b) * a.height) / 100)
this.setColor(this.hsb.h)
this.setValue(this.rgba)
this.bgcolor = this.HSBToRGB({
h: this.hsb.h,
s: 100,
b: 100
})
this.site[1].left = (this.hsb.h / 360) * b.width
this.site[2].left = this.rgba.a * c.width
},
/**
* hsb 转 rgb
* @param {Object} 颜色模式 H(hues)表示色相,S(saturation)表示饱和度,B(brightness)表示亮度
*/
HSBToRGB(hsb) {
let rgb = {}
let h = Math.round(hsb.h)
let s = Math.round((hsb.s * 255) / 100)
let v = Math.round((hsb.b * 255) / 100)
if (s == 0) {
rgb.r = rgb.g = rgb.b = v
} else {
let t1 = v
let t2 = ((255 - s) * v) / 255
let t3 = ((t1 - t2) * (h % 60)) / 60
if (h == 360) h = 0
if (h < 60) {
rgb.r = t1
rgb.b = t2
rgb.g = t2 + t3
} else if (h < 120) {
rgb.g = t1
rgb.b = t2
rgb.r = t1 - t3
} else if (h < 180) {
rgb.g = t1
rgb.r = t2
rgb.b = t2 + t3
} else if (h < 240) {
rgb.b = t1
rgb.r = t2
rgb.g = t1 - t3
} else if (h < 300) {
rgb.b = t1
rgb.g = t2
rgb.r = t2 + t3
} else if (h < 360) {
rgb.r = t1
rgb.g = t2
rgb.b = t1 - t3
} else {
rgb.r = 0
rgb.g = 0
rgb.b = 0
}
}
return {
r: Math.round(rgb.r),
g: Math.round(rgb.g),
b: Math.round(rgb.b)
}
},
rgbToHsb(rgb) {
let hsb = {
h: 0,
s: 0,
b: 0
}
let min = Math.min(rgb.r, rgb.g, rgb.b)
let max = Math.max(rgb.r, rgb.g, rgb.b)
let delta = max - min
hsb.b = max
hsb.s = max != 0 ? (255 * delta) / max : 0
if (hsb.s != 0) {
if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta
else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta
else hsb.h = 4 + (rgb.r - rgb.g) / delta
} else hsb.h = -1
hsb.h *= 60
if (hsb.h < 0) hsb.h = 0
hsb.s *= 100 / 255
hsb.b *= 100 / 255
return hsb
},
getSelectorQuery() {
const views = uni.createSelectorQuery().in(this)
views
.selectAll('.boxs')
.boundingClientRect((data) => {
if (!data || data.length === 0) {
setTimeout(() => this.getSelectorQuery(), 20)
return
}
this.position = data
// this.site[0].top = data[0].height;
// this.site[0].left = 0;
// this.site[1].left = data[1].width;
// this.site[2].left = data[2].width;
this.setColorBySelect(this.rgba)
})
.exec()
},
hex2Rgb(hexColor, alpha = 1) {
const color = hexColor.slice(1)
const r = parseInt(color.slice(0, 2), 16)
const g = parseInt(color.slice(2, 4), 16)
const b = parseInt(color.slice(4, 6), 16)
return {
r: r,
g: g,
b: b,
a: alpha
}
}
},
watch: {
spareColor(newVal) {
this.colorList = newVal
},
color(newVal) {
this.ready()
}
}
}
</script>
<style>
.t-wrapper {
position: fixed;
top: 0;
bottom: 0;
left: 0;
width: 100%;
box-sizing: border-box;
z-index: 9999;
}
.t-box {
width: 100%;
position: absolute;
bottom: 0;
padding: 30upx 0;
padding-top: 0;
background: #fff;
transition: all 0.3s;
transform: translateY(100%);
}
.t-box.active {
transform: translateY(0%);
}
.t-header {
display: flex;
justify-content: space-between;
width: 100%;
height: 100upx;
border-bottom: 1px #eee solid;
box-shadow: 1px 0 2px rgba(0, 0, 0, 0.1);
background: #fff;
}
.t-header-button {
display: flex;
align-items: center;
width: 150upx;
height: 100upx;
font-size: 30upx;
color: #666;
padding-left: 20upx;
}
.t-header-button:last-child {
justify-content: flex-end;
padding-right: 20upx;
}
.t-mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
z-index: -1;
transition: all 0.3s;
opacity: 0;
}
.t-mask.active {
opacity: 1;
}
.t-color__box {
position: relative;
height: 400upx;
background: rgb(255, 0, 0);
overflow: hidden;
box-sizing: border-box;
margin: 0 20upx;
margin-top: 20upx;
box-sizing: border-box;
}
.t-background {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(to right, #fff, rgba(255, 255, 255, 0));
}
.t-color-mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 400upx;
background: linear-gradient(to top, #000, rgba(0, 0, 0, 0));
}
.t-pointer {
position: absolute;
bottom: -8px;
left: -8px;
z-index: 2;
width: 15px;
height: 15px;
border: 1px #fff solid;
border-radius: 50%;
}
.t-show-color {
width: 100upx;
height: 50upx;
}
.t-control__box {
margin-top: 50upx;
width: 100%;
display: flex;
padding-left: 20upx;
box-sizing: border-box;
}
.t-control__color {
flex-shrink: 0;
width: 100upx;
height: 100upx;
border-radius: 50%;
background-color: #fff;
background-image: linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee),
linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee);
background-size: 36upx 36upx;
background-position: 0 0, 18upx 18upx;
border: 1px #eee solid;
overflow: hidden;
}
.t-control__color-content {
width: 100%;
height: 100%;
}
.t-control-box__item {
display: flex;
flex-direction: column;
justify-content: space-between;
width: 100%;
padding: 0 30upx;
}
.t-controller {
position: relative;
width: 100%;
height: 16px;
background-color: #fff;
background-image: linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee),
linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee);
background-size: 32upx 32upx;
background-position: 0 0, 16upx 16upx;
}
.t-hue {
width: 100%;
height: 100%;
background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);
}
.t-transparency {
width: 100%;
height: 100%;
background: linear-gradient(to right, rgba(0, 0, 0, 0) 0%, rgb(0, 0, 0));
}
.t-circle {
position: absolute;
/* right: -10px; */
top: -2px;
width: 20px;
height: 20px;
box-sizing: border-box;
border-radius: 50%;
background: #fff;
box-shadow: 0 0 2px 1px rgba(0, 0, 0, 0.1);
}
.t-result__box {
margin-top: 20upx;
padding: 10upx;
width: 100%;
display: flex;
box-sizing: border-box;
}
.t-result__item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 10upx;
width: 100%;
box-sizing: border-box;
}
.t-result__box-input {
padding: 10upx 0;
width: 100%;
font-size: 28upx;
box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.1);
color: #999;
text-align: center;
background: #fff;
}
.t-result__box-text {
margin-top: 10upx;
font-size: 28upx;
line-height: 2;
}
.t-select {
flex-shrink: 0;
width: 150upx;
padding: 0 30upx;
}
.t-select .t-result__box-input {
border-radius: 10upx;
border: none;
color: #999;
box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.1);
background: #fff;
}
.t-select .t-result__box-input:active {
box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.1);
}
.t-alternative {
display: flex;
flex-wrap: wrap;
/* justify-content: space-between; */
width: 100%;
padding-right: 10upx;
box-sizing: border-box;
}
.t-alternative__item {
margin-left: 12upx;
margin-top: 10upx;
width: 50upx;
height: 50upx;
border-radius: 10upx;
background-color: #fff;
background-image: linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee),
linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee);
background-size: 36upx 36upx;
background-position: 0 0, 18upx 18upx;
border: 1px #eee solid;
overflow: hidden;
}
.t-alternative__item-content {
width: 50upx;
height: 50upx;
background: rgba(255, 0, 0, 0.5);
}
.t-alternative__item:active {
transition: all 0.3s;
transform: scale(1.1);
}
</style>
<template>
<view class="link-edit-container" v-if="showPopup">
<view class="link-edit">
<view class="title">添加链接</view>
<view class="edit">
<view class="description">
链接描述:
<input v-model="descVal" type="text" class="input" placeholder="请输入链接描述" />
</view>
<view class="address">
链接地址:
<input v-model="addrVal" type="text" class="input" placeholder="请输入链接地址" />
</view>
</view>
<view class="control">
<view class="cancel" @click="close">取消</view>
<view class="confirm" @click="onConfirm">确认</view>
</view>
</view>
<view class="mask"></view>
</view>
</template>
<script>
export default {
data() {
return {
showPopup: false,
descVal: '',
addrVal: ''
}
},
methods: {
open() {
this.showPopup = true
this.$emit('open')
},
close() {
this.showPopup = false
this.descVal = ''
this.addrVal = ''
this.$emit('close')
},
onConfirm() {
if (!this.descVal) {
uni.showToast({
title: '请输入链接描述',
icon: 'none'
})
return
}
if (!this.addrVal) {
uni.showToast({
title: '请输入链接地址',
icon: 'none'
})
return
}
this.$emit('confirm', {
text: this.descVal,
href: this.addrVal
})
this.close()
}
}
}
</script>
<style lang="scss">
.link-edit-container {
.link-edit {
width: 80%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #ffffff;
box-shadow: -2px -2px 4px rgba(0, 0, 0, 0.05), 2px 2px 4px rgba(0, 0, 0, 0.05);
border-radius: 12rpx;
box-sizing: border-box;
z-index: 999;
font-size: 14px;
.title {
height: 80rpx;
display: flex;
justify-content: center;
align-items: center;
}
.edit {
padding: 24rpx;
border-top: 1px solid #eeeeee;
border-bottom: 1px solid #eeeeee;
box-sizing: border-box;
.input {
flex: 1;
padding: 4px;
font-size: 14px;
border: 1px solid #eeeeee;
border-radius: 8rpx;
.uni-input-placeholder {
color: #dddddd;
}
}
.description {
display: flex;
align-items: center;
}
.address {
display: flex;
align-items: center;
margin-top: 24rpx;
}
}
.control {
height: 80rpx;
display: flex;
cursor: pointer;
.cancel {
flex: 1;
color: #dd524d;
display: flex;
justify-content: center;
align-items: center;
}
.confirm {
border-left: 1px solid #eeeeee;
flex: 1;
color: #007aff;
display: flex;
justify-content: center;
align-items: center;
}
}
}
.mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.05);
z-index: 998;
}
}
</style>
<template>
<view class="sp-editor" :style="{ '--icon-size': iconSize, '--icon-columns': iconColumns }">
<view class="sp-editor-toolbar" v-if="!readOnly" @tap="format">
<view
v-if="toolbarList.includes('header')"
:class="formats.header === 1 ? 'ql-active' : ''"
class="iconfont icon-format-header-1"
title="标题"
data-name="header"
:data-value="1"
></view>
<view
v-if="toolbarList.includes('bold')"
:class="formats.bold ? 'ql-active' : ''"
class="iconfont icon-zitijiacu"
title="加粗"
data-name="bold"
></view>
<view
v-if="toolbarList.includes('italic')"
:class="formats.italic ? 'ql-active' : ''"
class="iconfont icon-zitixieti"
title="斜体"
data-name="italic"
></view>
<view
v-if="toolbarList.includes('underline')"
:class="formats.underline ? 'ql-active' : ''"
class="iconfont icon-zitixiahuaxian"
title="下划线"
data-name="underline"
></view>
<view
v-if="toolbarList.includes('strike')"
:class="formats.strike ? 'ql-active' : ''"
class="iconfont icon-zitishanchuxian"
title="删除线"
data-name="strike"
></view>
<!-- #ifndef MP-BAIDU -->
<view
v-if="toolbarList.includes('alignLeft')"
:class="formats.align === 'left' ? 'ql-active' : ''"
class="iconfont icon-zuoduiqi"
title="左对齐"
data-name="align"
data-value="left"
></view>
<!-- #endif -->
<view
v-if="toolbarList.includes('alignCenter')"
:class="formats.align === 'center' ? 'ql-active' : ''"
class="iconfont icon-juzhongduiqi"
title="居中对齐"
data-name="align"
data-value="center"
></view>
<view
v-if="toolbarList.includes('alignRight')"
:class="formats.align === 'right' ? 'ql-active' : ''"
class="iconfont icon-youduiqi"
title="右对齐"
data-name="align"
data-value="right"
></view>
<view
v-if="toolbarList.includes('alignJustify')"
:class="formats.align === 'justify' ? 'ql-active' : ''"
class="iconfont icon-zuoyouduiqi"
title="两端对齐"
data-name="align"
data-value="justify"
></view>
<!-- #ifndef MP-BAIDU -->
<view
v-if="toolbarList.includes('lineHeight')"
:class="formats.lineHeight ? 'ql-active' : ''"
class="iconfont icon-line-height"
title="行间距"
data-name="lineHeight"
data-value="2"
></view>
<view
v-if="toolbarList.includes('letterSpacing')"
:class="formats.letterSpacing ? 'ql-active' : ''"
class="iconfont icon-Character-Spacing"
title="字间距"
data-name="letterSpacing"
data-value="2em"
></view>
<view
v-if="toolbarList.includes('marginTop')"
:class="formats.marginTop ? 'ql-active' : ''"
class="iconfont icon-722bianjiqi_duanqianju"
title="段前距"
data-name="marginTop"
data-value="20px"
></view>
<view
v-if="toolbarList.includes('marginBottom')"
:class="formats.marginBottom ? 'ql-active' : ''"
class="iconfont icon-723bianjiqi_duanhouju"
title="段后距"
data-name="marginBottom"
data-value="20px"
></view>
<!-- #endif -->
<!-- #ifndef MP-BAIDU -->
<view
v-if="toolbarList.includes('fontSize')"
:class="formats.fontFamily ? 'ql-active' : ''"
class="iconfont icon-font"
title="字体"
data-name="fontFamily"
data-value="宋体"
></view>
<view
v-if="toolbarList.includes('fontSize')"
:class="formats.fontSize === '24px' ? 'ql-active' : ''"
class="iconfont icon-fontsize"
title="字号"
data-name="fontSize"
data-value="24px"
></view>
<!-- #endif -->
<view
v-if="toolbarList.includes('color')"
:style="{ color: formats.color ? textColor : 'initial' }"
class="iconfont icon-text_color"
title="文字颜色"
data-name="color"
:data-value="textColor"
></view>
<view
v-if="toolbarList.includes('backgroundColor')"
:style="{ color: formats.backgroundColor ? backgroundColor : 'initial' }"
class="iconfont icon-fontbgcolor"
title="背景颜色"
data-name="backgroundColor"
:data-value="backgroundColor"
></view>
<view
v-if="toolbarList.includes('date')"
class="iconfont icon-date"
title="日期"
@tap="insertDate"
></view>
<view
v-if="toolbarList.includes('listCheck')"
class="iconfont icon--checklist"
title="待办"
data-name="list"
data-value="check"
></view>
<view
v-if="toolbarList.includes('listOrdered')"
:class="formats.list === 'ordered' ? 'ql-active' : ''"
class="iconfont icon-youxupailie"
title="有序列表"
data-name="list"
data-value="ordered"
></view>
<view
v-if="toolbarList.includes('listBullet')"
:class="formats.list === 'bullet' ? 'ql-active' : ''"
class="iconfont icon-wuxupailie"
title="无序列表"
data-name="list"
data-value="bullet"
></view>
<view
v-if="toolbarList.includes('divider')"
class="iconfont icon-fengexian"
title="分割线"
@click="insertDivider"
></view>
<view
v-if="toolbarList.includes('indentDec')"
class="iconfont icon-outdent"
title="减少缩进"
data-name="indent"
data-value="-1"
></view>
<view
v-if="toolbarList.includes('indentInc')"
class="iconfont icon-indent"
title="增加缩进"
data-name="indent"
data-value="+1"
></view>
<view
v-if="toolbarList.includes('scriptSub')"
:class="formats.script === 'sub' ? 'ql-active' : ''"
class="iconfont icon-zitixiabiao"
title="下标"
data-name="script"
data-value="sub"
></view>
<view
v-if="toolbarList.includes('scriptSuper')"
:class="formats.script === 'super' ? 'ql-active' : ''"
class="iconfont icon-zitishangbiao"
title="上标"
data-name="script"
data-value="super"
></view>
<view
v-if="toolbarList.includes('direction')"
:class="formats.direction === 'rtl' ? 'ql-active' : ''"
class="iconfont icon-direction-rtl"
title="文本方向"
data-name="direction"
data-value="rtl"
></view>
<view
v-if="toolbarList.includes('image')"
class="iconfont icon-charutupian"
title="图片"
@tap="insertImage"
></view>
<view
v-if="toolbarList.includes('link')"
class="iconfont icon-charulianjie"
title="超链接"
@tap="insertLink"
></view>
<view
v-if="toolbarList.includes('undo')"
class="iconfont icon-undo"
title="撤销"
@tap="undo"
></view>
<view
v-if="toolbarList.includes('redo')"
class="iconfont icon-redo"
title="重做"
@tap="redo"
></view>
<view
v-if="toolbarList.includes('removeFormat')"
class="iconfont icon-clearedformat"
title="清除格式"
@tap="removeFormat"
></view>
<view
v-if="toolbarList.includes('clear')"
class="iconfont icon-shanchu"
title="清空"
@tap="clear"
></view>
<view
v-if="toolbarList.includes('export')"
class="iconfont icon-baocun"
title="导出"
@tap="exportHtml"
></view>
</view>
<!-- 自定义功能组件 -->
<!-- 调色板 -->
<color-picker
v-if="toolbarList.includes('color') || toolbarList.includes('backgroundColor')"
ref="colorPickerRef"
:color="defaultColor"
@confirm="confirmColor"
></color-picker>
<!-- 添加链接的操作弹窗 -->
<link-edit
v-if="toolbarList.includes('link') && !readOnly"
ref="linkEditRef"
@confirm="confirmLink"
></link-edit>
<view class="sp-editor-wrapper" @longpress="eLongpress">
<editor
:id="editorId"
class="ql-editor editor-container"
:class="{ 'ql-image-overlay-none': readOnly }"
show-img-size
show-img-toolbar
show-img-resize
:placeholder="placeholder"
:read-only="readOnly"
@statuschange="onStatusChange"
@ready="onEditorReady"
@input="onEditorInput"
></editor>
</view>
</view>
</template>
<script>
import ColorPicker from './color-picker.vue'
import LinkEdit from './link-edit.vue'
import { addLink, linkFlag } from '../../utils'
export default {
components: {
ColorPicker,
LinkEdit
},
props: {
// 编辑器id可传入,以便循环组件使用,防止id重复
editorId: {
type: String,
default: 'editor'
},
placeholder: {
type: String,
default: '写点什么吧 ~'
},
// 是否只读
readOnly: {
type: Boolean,
default: false
},
// 最大字数限制,-1不限
maxlength: {
type: Number,
default: -1
},
// 工具栏配置
toolbarConfig: {
type: Object,
default: () => {
return {
keys: [], // 要显示的工具,优先级最大
excludeKeys: [], // 除这些指定的工具外,其他都显示
iconSize: '18px', // 工具栏字体大小
iconColumns: 10 // 工具栏列数
}
}
}
},
watch: {
toolbarConfig: {
deep: true,
immediate: true,
handler(newToolbar) {
/**
* 若工具栏配置中keys存在,则以keys为准
* 否则以excludeKeys向toolbarAllList中排查
* 若keys与excludeKeys皆为空,则以toolbarAllList为准
*/
if (newToolbar.keys?.length > 0) {
this.toolbarList = newToolbar.keys
} else {
this.toolbarList =
newToolbar.excludeKeys?.length > 0
? this.toolbarAllList.filter((item) => !newToolbar.excludeKeys.includes(item))
: this.toolbarAllList
}
this.iconSize = newToolbar.iconSize || '18px'
this.iconColumns = newToolbar.iconColumns || 10
}
}
},
data() {
return {
formats: {},
textColor: '',
backgroundColor: '',
curColor: '',
defaultColor: { r: 0, g: 0, b: 0, a: 1 }, // 调色板默认颜色
iconSize: '20px', // 工具栏图标字体大小
iconColumns: 10, // 工具栏列数
toolbarList: [],
toolbarAllList: [
'bold', // 加粗
'italic', // 斜体
'underline', // 下划线
'strike', // 删除线
'alignLeft', // 左对齐
'alignCenter', // 居中对齐
'alignRight', // 右对齐
'alignJustify', // 两端对齐
'lineHeight', // 行间距
'letterSpacing', // 字间距
'marginTop', // 段前距
'marginBottom', // 段后距
'fontFamily', // 字体
'fontSize', // 字号
'color', // 文字颜色
'backgroundColor', // 背景颜色
'date', // 日期
'listCheck', // 待办
'listOrdered', // 有序列表
'listBullet', // 无序列表
'indentInc', // 增加缩进
'indentDec', // 减少缩进
'divider', // 分割线
'header', // 标题
'scriptSub', // 下标
'scriptSuper', // 上标
'direction', // 文本方向
'image', // 图片
'link', // 超链接
'undo', // 撤销
'redo', // 重做
'removeFormat', // 清除格式
'clear', // 清空
'export' // 导出
]
}
},
methods: {
onEditorReady() {
// #ifdef MP-BAIDU
this.editorCtx = requireDynamicLib('editorLib').createEditorContext(this.editorId)
// #endif
// #ifdef APP || MP-WEIXIN || H5
uni
.createSelectorQuery()
.in(this)
.select('#' + this.editorId)
.context((res) => {
this.editorCtx = res.context
this.$emit('init', this.editorCtx, this.editorId)
})
.exec()
// #endif
},
undo() {
this.editorCtx.undo()
},
redo() {
this.editorCtx.redo()
},
format(e) {
let { name, value } = e.target.dataset
if (!name) return
switch (name) {
case 'color':
case 'backgroundColor':
this.curColor = name
this.showPicker()
break
default:
this.editorCtx.format(name, value)
break
}
},
showPicker() {
switch (this.curColor) {
case 'color':
this.defaultColor = this.textColor
? this.$refs.colorPickerRef.hex2Rgb(this.textColor)
: { r: 0, g: 0, b: 0, a: 1 }
break
case 'backgroundColor':
this.defaultColor = this.backgroundColor
? this.$refs.colorPickerRef.hex2Rgb(this.backgroundColor)
: { r: 0, g: 0, b: 0, a: 0 }
break
}
this.$refs.colorPickerRef.open()
},
confirmColor(e) {
switch (this.curColor) {
case 'color':
this.textColor = e.hex
this.editorCtx.format('color', this.textColor)
break
case 'backgroundColor':
this.backgroundColor = e.hex
this.editorCtx.format('backgroundColor', this.backgroundColor)
break
}
},
onStatusChange(e) {
if (e.detail.color) {
this.textColor = e.detail.color
}
if (e.detail.backgroundColor) {
this.backgroundColor = e.detail.backgroundColor
}
this.formats = e.detail
},
insertDivider() {
this.editorCtx.insertDivider()
},
clear() {
uni.showModal({
title: '清空编辑器',
content: '确定清空编辑器吗?',
success: ({ confirm }) => {
if (confirm) {
this.editorCtx.clear()
}
}
})
},
removeFormat() {
uni.showModal({
title: '文本格式化',
content: '确定要清除所选择部分文本块格式吗?',
showCancel: true,
success: ({ confirm }) => {
if (confirm) {
this.editorCtx.removeFormat()
}
}
})
},
insertDate() {
const date = new Date()
const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
this.editorCtx.insertText({ text: formatDate })
},
insertLink() {
this.$refs.linkEditRef.open()
},
/**
* 确认添加链接
* @param {Object} e { text: '链接描述', href: '链接地址' }
*/
confirmLink(e) {
this.$refs.linkEditRef.close()
addLink(this.editorCtx, e)
this.$emit('addLink', e, this.editorId)
// 修复添加超链接后,不触发input更新当前最新内容的bug,这里做一下手动更新
this.editorCtx.getContents({
success: (res) => {
this.$emit('input', { html: res.html, text: res.text }, this.editorId)
}
})
},
insertImage() {
// #ifdef APP-PLUS || H5
uni.chooseImage({
// count: 1, // 默认9
success: (res) => {
const { tempFiles } = res
// 将文件和编辑器示例抛出,由开发者自行上传和插入图片
this.$emit('upinImage', tempFiles, this.editorCtx, this.editorId)
},
fail() {
uni.showToast({
title: '未授权访问相册权限,请授权后使用',
icon: 'none'
})
}
})
// #endif
// #ifdef MP-WEIXIN
// 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
uni.chooseMedia({
// count: 1, // 默认9
success: (res) => {
// 同上chooseImage处理
const { tempFiles } = res
this.$emit('upinImage', tempFiles, this.editorCtx, this.editorId)
},
fail() {
uni.showToast({
title: '未授权访问相册权限,请授权后使用',
icon: 'none'
})
}
})
// #endif
},
onEditorInput(e) {
// 注意不要使用getContents获取html和text,会导致重复触发onStatusChange从而失去toolbar工具的高亮状态
// 复制粘贴的时候detail会为空,此时应当直接return
if (Object.keys(e.detail).length <= 0) return
const { html, text } = e.detail
// 识别到标识立即return
if (text.indexOf(linkFlag) !== -1) return
const maxlength = parseInt(this.maxlength)
const textStr = text.replace(/[ \t\r\n]/g, '')
if (textStr.length > maxlength && maxlength != -1) {
uni.showModal({
content: `超过${maxlength}字数啦~`,
confirmText: '确定',
showCancel: false,
success: () => {
this.$emit('overMax', { html, text }, this.editorId)
}
})
} else {
this.$emit('input', { html, text }, this.editorId)
}
},
// 导出
exportHtml() {
this.editorCtx.getContents({
success: (res) => {
this.$emit('exportHtml', res.html, this.editorId)
}
})
},
eLongpress() {
/**
* 微信小程序官方editor的长按事件有bug,需要重写覆盖,不需做任何逻辑,可见下面小程序社区问题链接
* @tutorial https://developers.weixin.qq.com/community/develop/doc/000c04b3e1c1006f660065e4f61000
*/
}
}
}
</script>
<style lang="scss">
@import '@/uni_modules/sp-editor/icons/editor-icon.css';
.sp-editor {
height: 100%;
display: flex;
flex-direction: column;
position: relative;
}
.sp-editor-toolbar {
box-sizing: border-box;
padding: calc(var(--icon-size) / 4) 0;
border-bottom: 1px solid #e4e4e4;
font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
display: grid;
grid-template-columns: repeat(var(--icon-columns), 1fr);
}
.iconfont {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: calc(var(--icon-size) * 1.8);
cursor: pointer;
font-size: var(--icon-size);
}
.sp-editor-wrapper {
flex: 1;
overflow: hidden;
position: relative;
}
.editor-container {
padding: 8rpx 16rpx;
box-sizing: border-box;
width: 100%;
height: 100%;
font-size: 16px;
line-height: 1.5;
}
.ql-image-overlay-none {
::v-deep .ql-image-overlay {
pointer-events: none;
opacity: 0;
}
}
::v-deep .ql-editor.ql-blank::before {
font-style: normal;
color: #cccccc;
}
::v-deep .ql-container {
min-height: unset;
}
.ql-active {
color: #66ccff;
}
</style>
@font-face {
font-family: 'iconfont';
src: url('data:font/truetype;charset=utf-8;base64,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AAsAJgFuAAoAQwByAGUAYQB0AGUAZAAgAGIAeQAgAGkAYwBvAG4AZgBvAG4AdAAKAAAKQ3JlYXRlZCBieSBpY29uZm9udAoAAGkAYwBvAG4AZgBvAG4AdAAAaWNvbmZvbnQAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAGkAYwBvAG4AZgBvAG4AdAAAaWNvbmZvbnQAAGkAYwBvAG4AZgBvAG4AdAAAaWNvbmZvbnQAAFYAZQByAHMAaQBvAG4AIAAxAC4AMAAAVmVyc2lvbiAxLjAAAGkAYwBvAG4AZgBvAG4AdAAAaWNvbmZvbnQAAEcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAAcwB2AGcAMgB0AHQAZgAgAGYAcgBvAG0AIABGAG8AbgB0AGUAbABsAG8AIABwAHIAbwBqAGUAYwB0AC4AAEdlbmVyYXRlZCBieSBzdmcydHRmIGZyb20gRm9udGVsbG8gcHJvamVjdC4AAGgAdAB0AHAAOgAvAC8AZgBvAG4AdABlAGwAbABvAC4AYwBvAG0AAGh0dHA6Ly9mb250ZWxsby5jb20AAAIAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOwAAAAEAAgECAQMBBAEFAQYBBwEIAQkBCgELAQwBDQEOAQ8BEAERARIBEwEUARUBFgEXARgBGQEaARsBHAEdAR4BHwEgASEBIgEjASQBJQEmAScBKAEpASoBKwEsAS0BLgEvATABMQEyATMBNAE1ATYBNwE4ATkEcmVkbwlzZWxlY3RhbGwHcHJldmlldwR1bmRvBGRhdGUHY2xlYXJ1cBU3MjNiaWFuamlxaV9kdWFuaG91anUWNzIyYmlhbmppcWlfZHVhbnFpYW5qdQotY2hlY2tsaXN0DWRpcmVjdGlvbi1sdHINZGlyZWN0aW9uLXJ0bAtmb250Ymdjb2xvcg1jbGVhcmVkZm9ybWF0BGZvbnQHb3V0ZGVudAhmb250c2l6ZQp0ZXh0X2NvbG9yD2Zvcm1hdC1oZWFkZXItMg9mb3JtYXQtaGVhZGVyLTMLbGluZS1oZWlnaHQPZm9ybWF0LWhlYWRlci0xD2Zvcm1hdC1oZWFkZXItNA9mb3JtYXQtaGVhZGVyLTUPZm9ybWF0LWhlYWRlci02EUNoYXJhY3Rlci1TcGFjaW5nBmluZGVudAZiYW9jdW4IcXVhbnBpbmcFZnV6aGkHc2hhbmNodQxiaWFuamlzZWt1YWkJZmVuZ2V4aWFuB2RpYW56YW4MY2hhcnVsaWFuamllC2NoYXJ1dHVwaWFuCnd1eHVwYWlsaWUManV6aG9uZ2R1aXFpB3lpbnlvbmcLeW91eHVwYWlsaWUIeW91ZHVpcWkJeml0aWRhaW1hCHhpYW9saWFuCXppdGlqaWFjdQ96aXRpc2hhbmNodXhpYW4Neml0aXNoYW5nYmlhbwp6aXRpYmlhb3RpDnppdGl4aWFodWF4aWFuCXppdGl4aWV0aQl6aXRpeWFuc2UIenVvZHVpcWkJeml0aXl1bGFuC3ppdGl4aWFiaWFvC3p1b3lvdWR1aXFpB2R1aWdvdXgGZ3VhbmJpDnNoZW5neWluX3NoaXRpAAAAAAAB//8AAgABAAAADAAAABYAAAACAAEAAwA6AAEABAAAAAIAAAAAAAAAAQAAAADVpCcIAAAAANhk6GIAAAAA2GToYg==') format('truetype');
font-weight: normal;
font-style: normal;
font-display: swap;
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-redo:before {
content: "\e627";
}
.icon-undo:before {
content: "\e633";
}
.icon-indent:before {
content: "\eb28";
}
.icon-outdent:before {
content: "\e6e8";
}
.icon-fontsize:before {
content: "\e6fd";
}
.icon-format-header-1:before {
content: "\e860";
}
.icon-format-header-4:before {
content: "\e863";
}
.icon-format-header-5:before {
content: "\e864";
}
.icon-format-header-6:before {
content: "\e865";
}
.icon-clearup:before {
content: "\e64d";
}
.icon-preview:before {
content: "\e631";
}
.icon-date:before {
content: "\e63e";
}
.icon-fontbgcolor:before {
content: "\e678";
}
.icon-clearedformat:before {
content: "\e67e";
}
.icon-font:before {
content: "\e684";
}
.icon-723bianjiqi_duanhouju:before {
content: "\e65f";
}
.icon-722bianjiqi_duanqianju:before {
content: "\e660";
}
.icon-text_color:before {
content: "\e72c";
}
.icon-format-header-2:before {
content: "\e75c";
}
.icon-format-header-3:before {
content: "\e75d";
}
.icon--checklist:before {
content: "\e664";
}
.icon-baocun:before {
content: "\ec09";
}
.icon-line-height:before {
content: "\e7f8";
}
.icon-quanping:before {
content: "\ec13";
}
.icon-direction-rtl:before {
content: "\e66e";
}
.icon-direction-ltr:before {
content: "\e66d";
}
.icon-selectall:before {
content: "\e62b";
}
.icon-fuzhi:before {
content: "\ec7a";
}
.icon-shanchu:before {
content: "\ec7b";
}
.icon-bianjisekuai:before {
content: "\ec7c";
}
.icon-fengexian:before {
content: "\ec7f";
}
.icon-dianzan:before {
content: "\ec80";
}
.icon-charulianjie:before {
content: "\ec81";
}
.icon-charutupian:before {
content: "\ec82";
}
.icon-wuxupailie:before {
content: "\ec83";
}
.icon-juzhongduiqi:before {
content: "\ec84";
}
.icon-yinyong:before {
content: "\ec85";
}
.icon-youxupailie:before {
content: "\ec86";
}
.icon-youduiqi:before {
content: "\ec87";
}
.icon-zitidaima:before {
content: "\ec88";
}
.icon-xiaolian:before {
content: "\ec89";
}
.icon-zitijiacu:before {
content: "\ec8a";
}
.icon-zitishanchuxian:before {
content: "\ec8b";
}
.icon-zitishangbiao:before {
content: "\ec8c";
}
.icon-zitibiaoti:before {
content: "\ec8d";
}
.icon-zitixiahuaxian:before {
content: "\ec8e";
}
.icon-zitixieti:before {
content: "\ec8f";
}
.icon-zitiyanse:before {
content: "\ec90";
}
.icon-zuoduiqi:before {
content: "\ec91";
}
.icon-zitiyulan:before {
content: "\ec92";
}
.icon-zitixiabiao:before {
content: "\ec93";
}
.icon-zuoyouduiqi:before {
content: "\ec94";
}
.icon-duigoux:before {
content: "\ec9e";
}
.icon-guanbi:before {
content: "\eca0";
}
.icon-shengyin_shiti:before {
content: "\eca5";
}
.icon-Character-Spacing:before {
content: "\e964";
}
{
"id": "sp-editor",
"displayName": "官方富文本编辑器editor组件改良扩展优化版",
"version": "1.3.7",
"description": "基于官方的富文本编辑器editor组件,进行改良扩展优化版,添加了调色板,添加超链接等功能,可自定义扩展工具,快来试试吧~",
"keywords": [
"富文本",
"editor",
"编辑器"
],
"repository": "",
"engines": {
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "插件不采集任何数据",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "n"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "u",
"百度": "y",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}
\ No newline at end of file \ No newline at end of file
# sp-editor
### 文档迁移
> 防止文档失效,提供下列五个地址,内容一致
- [地址一](https://sonvee.github.io/sv-app-docs/docs-github/src/plugins/sp-editor/sp-editor.html)
- [地址二](https://sv-app-docs.pages.dev/src/plugins/sp-editor/sp-editor.html)
- [地址三](https://sv-app-docs.4everland.app/src/plugins/sp-editor/sp-editor.html)
- [地址四](https://sv-app-docs.vercel.app/src/plugins/sp-editor/sp-editor.html) (需要梯子)
- [地址五](https://static-mp-74bfcbac-6ba6-4f39-8513-8831390ff75a.next.bspapp.com/docs-uni/src/plugins/sp-editor/sp-editor.html) (有IP限制)
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ImageResize=e():t.ImageResize=e()}(this,function(){return function(t){function e(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return t[o].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=39)}([function(t,e){function n(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}t.exports=n},function(t,e,n){var o=n(22),r="object"==typeof self&&self&&self.Object===Object&&self,i=o||r||Function("return this")();t.exports=i},function(t,e){function n(t){return null!=t&&"object"==typeof t}t.exports=n},function(t,e,n){function o(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var o=t[e];this.set(o[0],o[1])}}var r=n(76),i=n(77),u=n(78),c=n(79),a=n(80);o.prototype.clear=r,o.prototype.delete=i,o.prototype.get=u,o.prototype.has=c,o.prototype.set=a,t.exports=o},function(t,e,n){function o(t,e){for(var n=t.length;n--;)if(r(t[n][0],e))return n;return-1}var r=n(8);t.exports=o},function(t,e,n){function o(t){return null==t?void 0===t?a:c:s&&s in Object(t)?i(t):u(t)}var r=n(16),i=n(65),u=n(88),c="[object Null]",a="[object Undefined]",s=r?r.toStringTag:void 0;t.exports=o},function(t,e,n){function o(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map}var r=n(74);t.exports=o},function(t,e,n){var o=n(11),r=o(Object,"create");t.exports=r},function(t,e){function n(t,e){return t===e||t!==t&&e!==e}t.exports=n},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}n.d(e,"a",function(){return r});var r=function t(e){o(this,t),this.onCreate=function(){},this.onDestroy=function(){},this.onUpdate=function(){},this.overlay=e.overlay,this.img=e.img,this.options=e.options,this.requestUpdate=e.onUpdate}},function(t,e,n){function o(t,e,n){"__proto__"==e&&r?r(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}var r=n(21);t.exports=o},function(t,e,n){function o(t,e){var n=i(t,e);return r(n)?n:void 0}var r=n(49),i=n(66);t.exports=o},function(t,e,n){function o(t){return null!=t&&i(t.length)&&!r(t)}var r=n(13),i=n(31);t.exports=o},function(t,e,n){function o(t){if(!i(t))return!1;var e=r(t);return e==c||e==a||e==u||e==s}var r=n(5),i=n(0),u="[object AsyncFunction]",c="[object Function]",a="[object GeneratorFunction]",s="[object Proxy]";t.exports=o},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){var o=n(11),r=n(1),i=o(r,"Map");t.exports=i},function(t,e,n){var o=n(1),r=o.Symbol;t.exports=r},function(t,e){function n(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}t.exports=n},function(t,e,n){function o(t,e,n){(void 0===n||i(t[e],n))&&(void 0!==n||e in t)||r(t,e,n)}var r=n(10),i=n(8);t.exports=o},function(t,e,n){function o(t,e,n,p,l){t!==e&&u(e,function(u,s){if(l||(l=new r),a(u))c(t,e,s,n,o,p,l);else{var d=p?p(f(t,s),u,s+"",t,e,l):void 0;void 0===d&&(d=u),i(t,s,d)}},s)}var r=n(42),i=n(18),u=n(47),c=n(52),a=n(0),s=n(33),f=n(26);t.exports=o},function(t,e,n){function o(t,e){return u(i(t,e,r),t+"")}var r=n(27),i=n(90),u=n(91);t.exports=o},function(t,e,n){var o=n(11),r=function(){try{var t=o(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=r},function(t,e,n){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,n(105))},function(t,e,n){var o=n(89),r=o(Object.getPrototypeOf,Object);t.exports=r},function(t,e){function n(t,e){var n=typeof t;return!!(e=null==e?o:e)&&("number"==n||"symbol"!=n&&r.test(t))&&t>-1&&t%1==0&&t<e}var o=9007199254740991,r=/^(?:0|[1-9]\d*)$/;t.exports=n},function(t,e){function n(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||o)}var o=Object.prototype;t.exports=n},function(t,e){function n(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}t.exports=n},function(t,e){function n(t){return t}t.exports=n},function(t,e,n){var o=n(48),r=n(2),i=Object.prototype,u=i.hasOwnProperty,c=i.propertyIsEnumerable,a=o(function(){return arguments}())?o:function(t){return r(t)&&u.call(t,"callee")&&!c.call(t,"callee")};t.exports=a},function(t,e){var n=Array.isArray;t.exports=n},function(t,e,n){(function(t){var o=n(1),r=n(103),i="object"==typeof e&&e&&!e.nodeType&&e,u=i&&"object"==typeof t&&t&&!t.nodeType&&t,c=u&&u.exports===i,a=c?o.Buffer:void 0,s=a?a.isBuffer:void 0,f=s||r;t.exports=f}).call(e,n(14)(t))},function(t,e){function n(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}var o=9007199254740991;t.exports=n},function(t,e,n){var o=n(50),r=n(55),i=n(87),u=i&&i.isTypedArray,c=u?r(u):o;t.exports=c},function(t,e,n){function o(t){return u(t)?r(t,!0):i(t)}var r=n(44),i=n(51),u=n(12);t.exports=o},function(t,e,n){"use strict";e.a={modules:["DisplaySize","Toolbar","Resize"]}},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}n.d(e,"a",function(){return c});var u=n(9),c=function(t){function e(){var t,n,i,u;o(this,e);for(var c=arguments.length,a=Array(c),s=0;s<c;s++)a[s]=arguments[s];return n=i=r(this,(t=e.__proto__||Object.getPrototypeOf(e)).call.apply(t,[this].concat(a))),i.onCreate=function(){i.display=document.createElement("div"),i.display.classList.add("ql-image-size"),i.overlay.appendChild(i.display)},i.onDestroy=function(){},i.onUpdate=function(){if(i.display&&i.img){var t=i.getCurrentSize();i.display.innerHTML=t.join(" &times; "),Object.assign(i.display.style,{right:"4px",top:"4px",left:"auto"})}},i.getCurrentSize=function(){return[i.img.width,Math.round(i.img.width/i.img.naturalWidth*i.img.naturalHeight)]},u=n,r(i,u)}return i(e,t),e}(u.a)},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}n.d(e,"a",function(){return f});var u=n(9),c=navigator.maxTouchPoints,a=!1;try{var s=Object.defineProperty({},"passive",{get:function(){a={passive:!1}}});window.addEventListener("test",null,s)}catch(t){}var f=function(t){function e(){var t,n,i,u;o(this,e);for(var s=arguments.length,f=Array(s),p=0;p<s;p++)f[p]=arguments[p];return n=i=r(this,(t=e.__proto__||Object.getPrototypeOf(e)).call.apply(t,[this].concat(f))),i.onCreate=function(){i.boxes=[],i.addBox("nwse-resize"),i.addBox("nesw-resize"),i.addBox("nwse-resize"),i.addBox("nesw-resize"),i.positionBoxes()},i.onDestroy=function(){i.setCursor("")},i.positionBoxes=function(){[{left:"-6px",top:"-6px"},{right:"-6px",top:"-6px"},{right:"-6px",bottom:"-6px"},{left:"-6px",bottom:"-6px"}].forEach(function(t,e){Object.assign(i.boxes[e].style,t)})},i.addBox=function(t){var e=document.createElement("div");e.classList.add("ql-image-handle"),e.style.cursor=t,e.addEventListener(c?"touchstart":"mousedown",i.handleMousedown,!1),i.overlay.appendChild(e),i.boxes.push(e)},i.handleMousedown=function(t){i.dragBox=t.target;var e=c?t.changedTouches[0]:t;i.dragStartX=e.clientX,i.preDragWidth=i.img.width||i.img.naturalWidth,i.setCursor(i.dragBox.style.cursor),document.addEventListener(c?"touchmove":"mousemove",i.handleDrag,a),document.addEventListener(c?"touchend":"mouseup",i.handleMouseup,!1)},i.handleMouseup=function(){i.setCursor(""),document.removeEventListener(c?"touchmove":"mousemove",i.handleDrag),document.removeEventListener(c?"touchend":"mouseup",i.handleMouseup)},i.handleDrag=function(t){if(i.img){var e=c?t.changedTouches[0]:t,n=e.clientX-i.dragStartX;i.dragBox===i.boxes[0]||i.dragBox===i.boxes[3]?i.img.width=Math.round(i.preDragWidth-n):i.img.width=Math.round(i.preDragWidth+n),i.requestUpdate(),t.preventDefault()}},i.setCursor=function(t){[document.body,i.img].forEach(function(e){e.style.cursor=t})},u=n,r(i,u)}return i(e,t),e}(u.a)},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}n.d(e,"a",function(){return c});var u=n(9),c=function(t){function e(){var t,n,i,u;o(this,e);for(var c=arguments.length,a=Array(c),s=0;s<c;s++)a[s]=arguments[s];return n=i=r(this,(t=e.__proto__||Object.getPrototypeOf(e)).call.apply(t,[this].concat(a))),i.onCreate=function(){i.toolbar=document.createElement("div"),i.toolbar.classList.add("ql-image-toolbar"),i.overlay.appendChild(i.toolbar),i._addToolbarButtons()},i.onDestroy=function(){},i.onUpdate=function(){},i._addToolbarButtons=function(){var t=document.createElement("span");t.classList.add("triangle-up"),i.toolbar.appendChild(t);var e=document.createElement("span");e.innerText="删除",e.addEventListener("click",function(){var t=new CustomEvent("keyup");t.keyCode=46,document.dispatchEvent(t)}),i.toolbar.appendChild(e)},u=n,r(i,u)}return i(e,t),e}(u.a)},function(t,e,n){var o=n(17),r=n(20),i=n(64),u=n(102),c=r(function(t){return t.push(void 0,i),o(u,void 0,t)});t.exports=c},function(t,e,n){"use strict";function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=n(38),i=n.n(r),u=n(34),c=n(35),a=n(37),s=n(36),f={DisplaySize:c.a,Toolbar:a.a,Resize:s.a},p=function t(e){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};o(this,t),this.initializeModules=function(){n.removeModules(),n.modules=n.moduleClasses.map(function(t){return new(f[t]||t)(n)}),n.modules.forEach(function(t){t.onCreate()}),n.onUpdate()},this.onUpdate=function(){n.repositionElements(),n.modules.forEach(function(t){t.onUpdate()})},this.removeModules=function(){n.modules.forEach(function(t){t.onDestroy()}),n.modules=[]},this.handleClick=function(t){if(t.target&&t.target.tagName&&"IMG"===t.target.tagName.toUpperCase()){if(n.img===t.target)return;n.img&&n.hide(),n.show(t.target)}else n.img&&n.hide()},this.show=function(t){n.img=t,n.showOverlay(),n.initializeModules()},this.showOverlay=function(){n.overlay&&n.hideOverlay(),n.quill.setSelection(null),n.setUserSelect("none"),document.addEventListener("keyup",n.checkImage,!0),n.quill.root.addEventListener("input",n.checkImage,!0),n.overlay=document.createElement("div"),n.overlay.classList.add("ql-image-overlay"),n.quill.root.parentNode.appendChild(n.overlay),n.repositionElements()},this.hideOverlay=function(){n.overlay&&(n.quill.root.parentNode.removeChild(n.overlay),n.overlay=void 0,document.removeEventListener("keyup",n.checkImage),n.quill.root.removeEventListener("input",n.checkImage),n.setUserSelect(""))},this.repositionElements=function(){if(n.overlay&&n.img){var t=n.quill.root.parentNode,e=n.img.getBoundingClientRect(),o=t.getBoundingClientRect();Object.assign(n.overlay.style,{left:e.left-o.left-1+t.scrollLeft+"px",top:e.top-o.top+t.scrollTop+"px",width:e.width+"px",height:e.height+"px"})}},this.hide=function(){n.hideOverlay(),n.removeModules(),n.img=void 0},this.setUserSelect=function(t){["userSelect","mozUserSelect","webkitUserSelect","msUserSelect"].forEach(function(e){n.quill.root.style[e]=t,document.documentElement.style[e]=t})},this.checkImage=function(t){n.img&&(46!=t.keyCode&&8!=t.keyCode||window.Quill.find(n.img).deleteAt(0),n.hide())},this.quill=e;var c=!1;r.modules&&(c=r.modules.slice()),this.options=i()({},r,u.a),!1!==c&&(this.options.modules=c),document.execCommand("enableObjectResizing",!1,"false"),this.quill.root.addEventListener("click",this.handleClick,!1),this.quill.root.parentNode.style.position=this.quill.root.parentNode.style.position||"relative",this.moduleClasses=this.options.modules,this.modules=[]};e.default=p,window.Quill&&window.Quill.register("modules/imageResize",p)},function(t,e,n){function o(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var o=t[e];this.set(o[0],o[1])}}var r=n(67),i=n(68),u=n(69),c=n(70),a=n(71);o.prototype.clear=r,o.prototype.delete=i,o.prototype.get=u,o.prototype.has=c,o.prototype.set=a,t.exports=o},function(t,e,n){function o(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var o=t[e];this.set(o[0],o[1])}}var r=n(81),i=n(82),u=n(83),c=n(84),a=n(85);o.prototype.clear=r,o.prototype.delete=i,o.prototype.get=u,o.prototype.has=c,o.prototype.set=a,t.exports=o},function(t,e,n){function o(t){var e=this.__data__=new r(t);this.size=e.size}var r=n(3),i=n(93),u=n(94),c=n(95),a=n(96),s=n(97);o.prototype.clear=i,o.prototype.delete=u,o.prototype.get=c,o.prototype.has=a,o.prototype.set=s,t.exports=o},function(t,e,n){var o=n(1),r=o.Uint8Array;t.exports=r},function(t,e,n){function o(t,e){var n=u(t),o=!n&&i(t),f=!n&&!o&&c(t),l=!n&&!o&&!f&&s(t),d=n||o||f||l,h=d?r(t.length,String):[],v=h.length;for(var y in t)!e&&!p.call(t,y)||d&&("length"==y||f&&("offset"==y||"parent"==y)||l&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||a(y,v))||h.push(y);return h}var r=n(54),i=n(28),u=n(29),c=n(30),a=n(24),s=n(32),f=Object.prototype,p=f.hasOwnProperty;t.exports=o},function(t,e,n){function o(t,e,n){var o=t[e];c.call(t,e)&&i(o,n)&&(void 0!==n||e in t)||r(t,e,n)}var r=n(10),i=n(8),u=Object.prototype,c=u.hasOwnProperty;t.exports=o},function(t,e,n){var o=n(0),r=Object.create,i=function(){function t(){}return function(e){if(!o(e))return{};if(r)return r(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();t.exports=i},function(t,e,n){var o=n(63),r=o();t.exports=r},function(t,e,n){function o(t){return i(t)&&r(t)==u}var r=n(5),i=n(2),u="[object Arguments]";t.exports=o},function(t,e,n){function o(t){return!(!u(t)||i(t))&&(r(t)?h:s).test(c(t))}var r=n(13),i=n(75),u=n(0),c=n(98),a=/[\\^$.*+?()[\]{}|]/g,s=/^\[object .+?Constructor\]$/,f=Function.prototype,p=Object.prototype,l=f.toString,d=p.hasOwnProperty,h=RegExp("^"+l.call(d).replace(a,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=o},function(t,e,n){function o(t){return u(t)&&i(t.length)&&!!c[r(t)]}var r=n(5),i=n(31),u=n(2),c={};c["[object Float32Array]"]=c["[object Float64Array]"]=c["[object Int8Array]"]=c["[object Int16Array]"]=c["[object Int32Array]"]=c["[object Uint8Array]"]=c["[object Uint8ClampedArray]"]=c["[object Uint16Array]"]=c["[object Uint32Array]"]=!0,c["[object Arguments]"]=c["[object Array]"]=c["[object ArrayBuffer]"]=c["[object Boolean]"]=c["[object DataView]"]=c["[object Date]"]=c["[object Error]"]=c["[object Function]"]=c["[object Map]"]=c["[object Number]"]=c["[object Object]"]=c["[object RegExp]"]=c["[object Set]"]=c["[object String]"]=c["[object WeakMap]"]=!1,t.exports=o},function(t,e,n){function o(t){if(!r(t))return u(t);var e=i(t),n=[];for(var o in t)("constructor"!=o||!e&&a.call(t,o))&&n.push(o);return n}var r=n(0),i=n(25),u=n(86),c=Object.prototype,a=c.hasOwnProperty;t.exports=o},function(t,e,n){function o(t,e,n,o,g,_,m){var j=b(t,n),w=b(e,n),O=m.get(w);if(O)return void r(t,n,O);var E=_?_(j,w,n+"",t,e,m):void 0,z=void 0===E;if(z){var C=f(w),P=!C&&l(w),S=!C&&!P&&y(w);E=w,C||P||S?f(j)?E=j:p(j)?E=c(j):P?(z=!1,E=i(w,!0)):S?(z=!1,E=u(w,!0)):E=[]:v(w)||s(w)?(E=j,s(j)?E=x(j):h(j)&&!d(j)||(E=a(w))):z=!1}z&&(m.set(w,E),g(E,w,o,_,m),m.delete(w)),r(t,n,E)}var r=n(18),i=n(57),u=n(58),c=n(59),a=n(72),s=n(28),f=n(29),p=n(100),l=n(30),d=n(13),h=n(0),v=n(101),y=n(32),b=n(26),x=n(104);t.exports=o},function(t,e,n){var o=n(99),r=n(21),i=n(27),u=r?function(t,e){return r(t,"toString",{configurable:!0,enumerable:!1,value:o(e),writable:!0})}:i;t.exports=u},function(t,e){function n(t,e){for(var n=-1,o=Array(t);++n<t;)o[n]=e(n);return o}t.exports=n},function(t,e){function n(t){return function(e){return t(e)}}t.exports=n},function(t,e,n){function o(t){var e=new t.constructor(t.byteLength);return new r(e).set(new r(t)),e}var r=n(43);t.exports=o},function(t,e,n){(function(t){function o(t,e){if(e)return t.slice();var n=t.length,o=s?s(n):new t.constructor(n);return t.copy(o),o}var r=n(1),i="object"==typeof e&&e&&!e.nodeType&&e,u=i&&"object"==typeof t&&t&&!t.nodeType&&t,c=u&&u.exports===i,a=c?r.Buffer:void 0,s=a?a.allocUnsafe:void 0;t.exports=o}).call(e,n(14)(t))},function(t,e,n){function o(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}var r=n(56);t.exports=o},function(t,e){function n(t,e){var n=-1,o=t.length;for(e||(e=Array(o));++n<o;)e[n]=t[n];return e}t.exports=n},function(t,e,n){function o(t,e,n,o){var u=!n;n||(n={});for(var c=-1,a=e.length;++c<a;){var s=e[c],f=o?o(n[s],t[s],s,n,t):void 0;void 0===f&&(f=t[s]),u?i(n,s,f):r(n,s,f)}return n}var r=n(45),i=n(10);t.exports=o},function(t,e,n){var o=n(1),r=o["__core-js_shared__"];t.exports=r},function(t,e,n){function o(t){return r(function(e,n){var o=-1,r=n.length,u=r>1?n[r-1]:void 0,c=r>2?n[2]:void 0;for(u=t.length>3&&"function"==typeof u?(r--,u):void 0,c&&i(n[0],n[1],c)&&(u=r<3?void 0:u,r=1),e=Object(e);++o<r;){var a=n[o];a&&t(e,a,o,u)}return e})}var r=n(20),i=n(73);t.exports=o},function(t,e){function n(t){return function(e,n,o){for(var r=-1,i=Object(e),u=o(e),c=u.length;c--;){var a=u[t?c:++r];if(!1===n(i[a],a,i))break}return e}}t.exports=n},function(t,e,n){function o(t,e,n,u,c,a){return i(t)&&i(e)&&(a.set(e,t),r(t,e,void 0,o,a),a.delete(e)),t}var r=n(19),i=n(0);t.exports=o},function(t,e,n){function o(t){var e=u.call(t,a),n=t[a];try{t[a]=void 0;var o=!0}catch(t){}var r=c.call(t);return o&&(e?t[a]=n:delete t[a]),r}var r=n(16),i=Object.prototype,u=i.hasOwnProperty,c=i.toString,a=r?r.toStringTag:void 0;t.exports=o},function(t,e){function n(t,e){return null==t?void 0:t[e]}t.exports=n},function(t,e,n){function o(){this.__data__=r?r(null):{},this.size=0}var r=n(7);t.exports=o},function(t,e){function n(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}t.exports=n},function(t,e,n){function o(t){var e=this.__data__;if(r){var n=e[t];return n===i?void 0:n}return c.call(e,t)?e[t]:void 0}var r=n(7),i="__lodash_hash_undefined__",u=Object.prototype,c=u.hasOwnProperty;t.exports=o},function(t,e,n){function o(t){var e=this.__data__;return r?void 0!==e[t]:u.call(e,t)}var r=n(7),i=Object.prototype,u=i.hasOwnProperty;t.exports=o},function(t,e,n){function o(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=r&&void 0===e?i:e,this}var r=n(7),i="__lodash_hash_undefined__";t.exports=o},function(t,e,n){function o(t){return"function"!=typeof t.constructor||u(t)?{}:r(i(t))}var r=n(46),i=n(23),u=n(25);t.exports=o},function(t,e,n){function o(t,e,n){if(!c(n))return!1;var o=typeof e;return!!("number"==o?i(n)&&u(e,n.length):"string"==o&&e in n)&&r(n[e],t)}var r=n(8),i=n(12),u=n(24),c=n(0);t.exports=o},function(t,e){function n(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}t.exports=n},function(t,e,n){function o(t){return!!i&&i in t}var r=n(61),i=function(){var t=/[^.]+$/.exec(r&&r.keys&&r.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();t.exports=o},function(t,e){function n(){this.__data__=[],this.size=0}t.exports=n},function(t,e,n){function o(t){var e=this.__data__,n=r(e,t);return!(n<0)&&(n==e.length-1?e.pop():u.call(e,n,1),--this.size,!0)}var r=n(4),i=Array.prototype,u=i.splice;t.exports=o},function(t,e,n){function o(t){var e=this.__data__,n=r(e,t);return n<0?void 0:e[n][1]}var r=n(4);t.exports=o},function(t,e,n){function o(t){return r(this.__data__,t)>-1}var r=n(4);t.exports=o},function(t,e,n){function o(t,e){var n=this.__data__,o=r(n,t);return o<0?(++this.size,n.push([t,e])):n[o][1]=e,this}var r=n(4);t.exports=o},function(t,e,n){function o(){this.size=0,this.__data__={hash:new r,map:new(u||i),string:new r}}var r=n(40),i=n(3),u=n(15);t.exports=o},function(t,e,n){function o(t){var e=r(this,t).delete(t);return this.size-=e?1:0,e}var r=n(6);t.exports=o},function(t,e,n){function o(t){return r(this,t).get(t)}var r=n(6);t.exports=o},function(t,e,n){function o(t){return r(this,t).has(t)}var r=n(6);t.exports=o},function(t,e,n){function o(t,e){var n=r(this,t),o=n.size;return n.set(t,e),this.size+=n.size==o?0:1,this}var r=n(6);t.exports=o},function(t,e){function n(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e}t.exports=n},function(t,e,n){(function(t){var o=n(22),r="object"==typeof e&&e&&!e.nodeType&&e,i=r&&"object"==typeof t&&t&&!t.nodeType&&t,u=i&&i.exports===r,c=u&&o.process,a=function(){try{var t=i&&i.require&&i.require("util").types;return t||c&&c.binding&&c.binding("util")}catch(t){}}();t.exports=a}).call(e,n(14)(t))},function(t,e){function n(t){return r.call(t)}var o=Object.prototype,r=o.toString;t.exports=n},function(t,e){function n(t,e){return function(n){return t(e(n))}}t.exports=n},function(t,e,n){function o(t,e,n){return e=i(void 0===e?t.length-1:e,0),function(){for(var o=arguments,u=-1,c=i(o.length-e,0),a=Array(c);++u<c;)a[u]=o[e+u];u=-1;for(var s=Array(e+1);++u<e;)s[u]=o[u];return s[e]=n(a),r(t,this,s)}}var r=n(17),i=Math.max;t.exports=o},function(t,e,n){var o=n(53),r=n(92),i=r(o);t.exports=i},function(t,e){function n(t){var e=0,n=0;return function(){var u=i(),c=r-(u-n);if(n=u,c>0){if(++e>=o)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var o=800,r=16,i=Date.now;t.exports=n},function(t,e,n){function o(){this.__data__=new r,this.size=0}var r=n(3);t.exports=o},function(t,e){function n(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}t.exports=n},function(t,e){function n(t){return this.__data__.get(t)}t.exports=n},function(t,e){function n(t){return this.__data__.has(t)}t.exports=n},function(t,e,n){function o(t,e){var n=this.__data__;if(n instanceof r){var o=n.__data__;if(!i||o.length<c-1)return o.push([t,e]),this.size=++n.size,this;n=this.__data__=new u(o)}return n.set(t,e),this.size=n.size,this}var r=n(3),i=n(15),u=n(41),c=200;t.exports=o},function(t,e){function n(t){if(null!=t){try{return r.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var o=Function.prototype,r=o.toString;t.exports=n},function(t,e){function n(t){return function(){return t}}t.exports=n},function(t,e,n){function o(t){return i(t)&&r(t)}var r=n(12),i=n(2);t.exports=o},function(t,e,n){function o(t){if(!u(t)||r(t)!=c)return!1;var e=i(t);if(null===e)return!0;var n=p.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&f.call(n)==l}var r=n(5),i=n(23),u=n(2),c="[object Object]",a=Function.prototype,s=Object.prototype,f=a.toString,p=s.hasOwnProperty,l=f.call(Object);t.exports=o},function(t,e,n){var o=n(19),r=n(62),i=r(function(t,e,n,r){o(t,e,n,r)});t.exports=i},function(t,e){function n(){return!1}t.exports=n},function(t,e,n){function o(t){return r(t,i(t))}var r=n(60),i=n(33);t.exports=o},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n}])});
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
// 标识必须独一无二 - 标识是为了使用insertText插入标识文本后,查找到标识所在delta位置的索引
export const linkFlag = '#-*=*-*=*-*=*@-link超链接标识link-@*=*-*=*-*=*-#'
export function addLink(editorCtx, attr) {
// 先插入一段文本内容
editorCtx.insertText({
text: linkFlag
})
// 获取全文delta内容
editorCtx.getContents({
success(res) {
let options = res.delta.ops
const findex = options.findIndex(item => {
return item.insert && typeof item.insert !== 'object' && item.insert?.indexOf(linkFlag) !== -1
})
// 根据标识查找到插入的位置
if (findex > -1) {
const findOption = options[findex]
const findAttributes = findOption.attributes
// 将该findOption分成三部分:前内容 要插入的link 后内容
const [prefix, suffix] = findOption.insert.split(linkFlag);
const handleOps = []
// 前内容
if (prefix) {
const prefixOps = findAttributes ? {
insert: prefix,
attributes: findAttributes
} : {
insert: prefix
}
handleOps.push(prefixOps)
}
// 插入的link
const linkOps = {
insert: attr.text,
attributes: {
link: attr.href,
textDecoration: attr.textDecoration || 'none', // 下划线
color: attr.color || '#007aff'
}
}
handleOps.push(linkOps)
// 后内容
if (suffix) {
const suffixOps = findAttributes ? {
insert: suffix,
attributes: findAttributes
} : {
insert: suffix
}
handleOps.push(suffixOps)
}
// 删除原options[findex]并在findex位置插入上述三个ops
options.splice(findex, 1);
options.splice(findex, 0, ...handleOps);
// 最后重新初始化内容,注意该方法会导致光标重置到最开始位置
editorCtx.setContents({
delta: {
ops: options
}
})
// 所以最后建议使富文本光标失焦,让用户手动聚焦光标
editorCtx.blur()
}
}
})
}
\ No newline at end of file \ No newline at end of file
import { CustomRequestOptions } from '@/interceptors/request'
export const http = <T>(options: CustomRequestOptions) => {
// 1. 返回 Promise 对象
return new Promise<IResData<T>>((resolve, reject) => {
uni.request({
...options,
dataType: 'json',
// #ifndef MP-WEIXIN
responseType: 'json',
// #endif
// 响应成功
success(res) {
// 状态码 2xx,参考 axios 的设计
if (res.statusCode >= 200 && res.statusCode < 300) {
// 2.1 提取核心数据 res.data
resolve(res.data as IResData<T>)
} else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
// userStore.clearUserInfo()
// uni.navigateTo({ url: '/pages/login/login' })
reject(res)
} else {
// 其他错误 -> 根据后端错误信息轻提示
uni.showToast({
icon: 'none',
title: (res.data as IResData<T>).msg || '请求错误',
})
reject(res)
}
},
// 响应失败
fail(err) {
uni.showToast({
icon: 'none',
title: '网络错误,换个网络试试',
})
reject(err)
},
})
})
}
// uni.uploadFile封装
export const uniFileUpload = <T>(options: CustomRequestOptions) => {
// 1. 返回 Promise 对象
return new Promise<IResData<T>>((resolve, reject) => {
uni.uploadFile({
...options,
// 响应成功
success(res) {
// 状态码 2xx,参考 axios 的设计
if (res.statusCode >= 200 && res.statusCode < 300) {
// 文件上传接口的rea.data的类型为string,这里转一下
const resData = JSON.parse(res.data) as IResData<T>
resolve(resData)
} else if (res.statusCode === 401) {
// 401错误 -> 清理用户信息,跳转到登录页
// userStore.clearUserInfo()
// uni.navigateTo({ url: '/pages/login/login' })
reject(res)
} else {
// 其他错误 -> 根据后端错误信息轻提示
uni.showToast({
icon: 'none',
title: '文件上传错误',
})
reject(res)
}
},
// 响应失败
fail(err) {
uni.showToast({
icon: 'none',
title: '网络错误,换个网络试试',
})
reject(err)
},
})
})
}
import pagesJson from '@/pages.json'
import { translate as t } from '@/locale/index'
console.log(pagesJson)
/** 判断当前页面是否是tabbar页 */
export const getIsTabbar = () => {
if (!Object.keys(pagesJson).includes('tabBar')) {
return false
}
const pages = getCurrentPages()
const lastPage = getLastItem(pages)
const currPath = lastPage.route
return !!pagesJson.tabBar.list.find((e) => e.pagePath === currPath)
}
/**
* test i18n in not .vue file
*/
export const testI18n = () => {
console.log(t('app.name'))
// 下面同样生效
uni.showModal({
title: 'i18n 测试',
content: t('app.name'),
})
}
/**
* 获取当前页面路由的 path 路劲和 redirectPath 路径
* path 如 ‘/pages/login/index’
* redirectPath 如 ‘/pages/demo/base/route-interceptor’
*/
export const currRoute = () => {
const pages = getCurrentPages()
console.log('pages:', pages)
const lastPage = getLastItem(pages)
const currRoute = (lastPage as any).$page
// console.log('lastPage.$page:', currRoute)
// console.log('lastPage.$page.fullpath:', currRoute.fullPath)
// console.log('lastPage.$page.options:', currRoute.options)
// console.log('lastPage.options:', (lastPage as any).options)
// 经过多端测试,只有 fullPath 靠谱,其他都不靠谱
const { fullPath } = currRoute as { fullPath: string }
console.log(fullPath)
// eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
// eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
return getUrlObj(fullPath)
}
const ensureDecodeURIComponent = (url: string) => {
if (url.startsWith('%')) {
return ensureDecodeURIComponent(decodeURIComponent(url))
}
return url
}
/**
* 解析 url 得到 path 和 query
* 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
* 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
*/
export const getUrlObj = (url: string) => {
const [path, queryStr] = url.split('?')
console.log(path, queryStr)
const query: Record<string, string> = {}
queryStr.split('&').forEach((item) => {
const [key, value] = item.split('=')
console.log(key, value)
query[key] = ensureDecodeURIComponent(value) // 这里需要统一 decodeURIComponent 一下,可以兼容h5和微信y
})
return { path, query }
}
/**
* 得到所有的需要登录的pages,包括主包和分包的
* 这里设计得通用一点,可以传递key作为判断依据,默认是 needLogin, 与 route-block 配对使用
* 如果没有传 key,则表示所有的pages,如果传递了 key, 则表示通过 key 过滤
*/
export const getAllPages = (key = 'needLogin') => {
// 这里处理主包
const pages = [
...pagesJson.pages
.filter((page) => !key || page[key])
.map((page) => ({
...page,
path: `/${page.path}`,
})),
]
// 这里处理分包
const subPages: any[] = []
pagesJson.subPackages.forEach((subPageObj) => {
// console.log(subPageObj)
const { root } = subPageObj
subPageObj.pages
.filter((page) => !key || page[key])
.forEach((page: { path: string } & Record<string, any>) => {
subPages.push({
...page,
path: `/${root}/${page.path}`,
})
})
})
const result = [...pages, ...subPages]
console.log(`getAllPages by ${key} result: `, result)
return result
}
/**
* 得到所有的需要登录的pages,包括主包和分包的
* 只得到 path 数组
*/
export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)
/**
* 得到所有的需要登录的pages,包括主包和分包的
* 只得到 path 数组
*/
export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)
/** 主要是处理 arr.at(-1) 在安卓机上运行报错的 兼容性问题 */
export const getArrElementByIdx = (arr: any[], index: number) => {
if (index < 0) return arr[arr.length + index]
if (index >= arr.length) return undefined
return arr[index]
}
export const getLastItem = (arr: any[]) => getArrElementByIdx(arr, -1)
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"outDir": "dist",
"lib": ["esnext", "dom"],
"types": [
"./vite-env.d.ts",
"@dcloudio/types",
"@types/wechat-miniprogram",
"@uni-helper/uni-ui-types",
"wot-design-uni/global.d.ts",
"@ttou/uv-typings/shim",
"@ttou/uv-typings/v2"
]
},
"vueCompilerOptions": {
"target": 3,
"nativeTags": ["block", "template", "component", "slot"]
},
"exclude": ["node_modules"],
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/**/*.json",
"mock/_mockProdServer.ts"
]
}
declare type Recordable<T = any> = Record<string, T>
// uno.config.ts
import {
type Preset,
type SourceCodeTransformer,
presetUno,
defineConfig,
presetAttributify,
presetIcons,
transformerDirectives,
transformerVariantGroup,
} from 'unocss'
import {
presetApplet,
presetRemRpx,
transformerApplet,
transformerAttributify,
} from 'unocss-applet'
// @see https://unocss.dev/presets/legacy-compat
import presetLegacyCompat from '@unocss/preset-legacy-compat'
const isMp = process.env?.UNI_PLATFORM?.startsWith('mp') ?? false
const presets: Preset[] = []
const transformers: SourceCodeTransformer[] = []
if (isMp) {
// 使用小程序预设
presets.push(presetApplet(), presetRemRpx())
transformers.push(transformerApplet())
} else {
presets.push(
// 非小程序用官方预设
presetUno(),
// 支持css class属性化
presetAttributify(),
)
}
export default defineConfig({
presets: [
...presets,
// 支持图标,需要搭配图标库,eg: @iconify-json/carbon, 使用 `<button class="i-carbon-sun dark:i-carbon-moon" />`
presetIcons({
scale: 1.2,
warn: true,
extraProperties: {
display: 'inline-block',
'vertical-align': 'middle',
},
}),
// 将颜色函数 (rgb()和hsl()) 从空格分隔转换为逗号分隔,更好的兼容性app端,example:
// `rgb(255 0 0)` -> `rgb(255, 0, 0)`
// `rgba(255 0 0 / 0.5)` -> `rgba(255, 0, 0, 0.5)`
presetLegacyCompat({
commaStyleColorFunction: true,
}) as Preset,
],
/**
* 自定义快捷语句
* @see https://github.com/unocss/unocss#shortcuts
*/
shortcuts: [
['center', 'flex justify-center items-center'],
['text-primary', 'text-yellow'],
],
transformers: [
...transformers,
// 启用 @apply 功能
transformerDirectives(),
// 启用 () 分组功能
// 支持css class组合,eg: `<div class="hover:(bg-gray-400 font-medium) font-(light mono)">测试 unocss</div>`
transformerVariantGroup(),
// Don't change the following order
transformerAttributify({
// 解决与第三方框架样式冲突问题
prefixedOnly: true,
prefix: 'fg',
}),
],
rules: [
[
'p-safe',
{
padding:
'env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)',
},
],
['pt-safe', { 'padding-top': 'env(safe-area-inset-top)' }],
['pb-safe', { 'padding-bottom': 'env(safe-area-inset-bottom)' }],
],
})
/**
* 最终这一套组合下来会得到:
* mp 里面:mt-4 => margin-top: 32rpx
* h5 里面:mt-4 => margin-top: 1rem
*/
// 全局自定义参数
declare const __UNI_PLATFORM__:
| 'h5'
| 'app'
| 'mp-alipay'
| 'mp-baidu'
| 'mp-jd'
| 'mp-kuaishou'
| 'mp-lark'
| 'mp-qq'
| 'mp-toutiao'
| 'mp-weixin'
| 'quickapp-webview'
| 'quickapp-webview-huawei'
| 'quickapp-webview-union'
// TIPS: 很多用户无法安装这个插件所以先注释掉了,如果您可以安装成功,那就可以放开这个注释,以及下面的viteImagemin配置
// 注意,小程序有主包2M的限制,所以一般图片会放到图片服务器(不放本地),那就不需要这个插件
import viteImagemin from 'vite-plugin-imagemin'
export default (enabled: boolean) => {
if (!enabled) {
return undefined
}
return viteImagemin({
gifsicle: {
// gif图片压缩
optimizationLevel: 3, // 选择1到3之间的优化级别
interlaced: false, // 隔行扫描gif进行渐进式渲染
// colors: 2 // 将每个输出GIF中不同颜色的数量减少到num或更少。数字必须介于2和256之间。
},
optipng: {
// png
optimizationLevel: 7, // 选择0到7之间的优化级别
},
mozjpeg: {
// jpeg
quality: 20, // 压缩质量,范围从0(最差)到100(最佳)。
},
pngquant: {
// png
quality: [0.8, 0.9], // Min和max是介于0(最差)到1(最佳)之间的数字,类似于JPEG。达到或超过最高质量所需的最少量的颜色。如果转换导致质量低于最低质量,图像将不会被保存。
speed: 4, // 压缩速度,1(强力)到11(最快)
},
svgo: {
// svg压缩
plugins: [
{
name: 'removeViewBox',
},
{
name: 'removeEmptyAttrs',
active: false,
},
],
},
})
}
import path from 'node:path'
import dayjs from 'dayjs'
import { defineConfig, loadEnv } from 'vite'
import Uni from '@dcloudio/vite-plugin-uni'
// @see https://uni-helper.js.org/vite-plugin-uni-pages
import UniPages from '@uni-helper/vite-plugin-uni-pages'
// @see https://uni-helper.js.org/vite-plugin-uni-layouts
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
// @see https://github.com/uni-helper/vite-plugin-uni-platform
// 需要与 @uni-helper/vite-plugin-uni-pages 插件一起使用
import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
// @see https://github.com/uni-helper/vite-plugin-uni-manifest
import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
// @see https://github.com/uni-helper/vite-plugin-uni-components
import Components from '@uni-helper/vite-plugin-uni-components'
// @see https://unocss.dev/
import UnoCSS from 'unocss/vite'
// import autoprefixer from 'autoprefixer'
// @see https://github.com/jpkleemans/vite-svg-loader
import svgLoader from 'vite-svg-loader'
// @see https://github.com/vbenjs/vite-plugin-svg-icons
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// @see https://github.com/vbenjs/vite-plugin-vue-setup-extend
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import AutoImport from 'unplugin-auto-import/vite'
// import viteCompression from 'vite-plugin-compression'
import ViteRestart from 'vite-plugin-restart'
import { visualizer } from 'rollup-plugin-visualizer'
import imagemin from './vite-plugins/imagemin'
console.log('process.platform -> ', process.platform)
// https://vitejs.dev/config/
export default ({ command, mode }) => {
// console.log(mode === process.env.NODE_ENV) // true
// mode: 区分生产环境还是开发环境
console.log('command, mode -> ', command, mode)
// pnpm dev:h5 时得到 => serve development
// pnpm build:h5 时得到 => build production
// pnpm dev:mp-weixin 时得到 => build development (注意区别,command为build)
// pnpm build:mp-weixin 时得到 => build production
// process.cwd(): 获取当前文件的目录跟地址
// loadEnv(): 返回当前环境env文件中额外定义的变量
const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
console.log('env -> ', env)
console.log('process.env.UNI_PLATFORM: ', process.env.UNI_PLATFORM) // 得到 mp-weixin, h5, app 等
console.log('isH5: ', process.env.UNI_PLATFORM === 'h5') // 得到 mp-weixin, h5, app 等
return defineConfig({
envDir: './env', // 自定义env目录
plugins: [
UniPages({
dts: 'src/types/uni-pages.d.ts',
exclude: ['**/components/**/**.*'],
routeBlockLang: 'json5', // 虽然设了默认值,但是vue文件还是要加上 lang="json5", 这样才能很好地格式化
homePage: 'pages/index/index',
subPackages: ['src/pages-sub'], // 是个数组,可以配置多个
}),
UniLayouts(),
UniPlatform(),
UniManifest(),
// 自动安装 src/components 里面的组件为全局组件,非全局组件不要放到 src/components
Components({
dts: 'src/types/components.d.ts',
}),
// UniXXX 需要在 Uni 之前引入
Uni(),
UnoCSS(),
// svg 可以当做组件来使用(Vite plugin to load SVG files as Vue components, using SVGO for optimization.)
svgLoader({
defaultImport: 'url', // or 'raw'
}),
createSvgIconsPlugin({
// 指定要缓存的文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
}),
vueSetupExtend(),
AutoImport({
imports: ['vue', 'uni-app'],
dts: 'src/types/auto-import.d.ts',
dirs: ['src/hooks'], // 自动导入 hooks
eslintrc: { enabled: false },
vueTemplate: true, // default false
}),
// viteCompression(),
ViteRestart({
// 通过这个插件,在修改vite.config.js文件则不需要重新运行也生效配置
restart: ['vite.config.js'],
}),
// h5环境增加编译时间
process.env.UNI_PLATFORM === 'h5' && {
name: 'html-transform',
transformIndexHtml(html) {
return html.replace('%BUILD_DATE%', dayjs().format('YYYY-MM-DD HH:mm:ss'))
},
},
// 打包分析插件
mode === 'production' &&
visualizer({
filename: './node_modules/.cache/visualizer/stats.html',
open: true,
gzipSize: true,
brotliSize: true,
}),
// 这个图片压缩插件比较耗时,希望仅在生产环境使用
// TODO: 缓存每次压缩过的图片,已经压缩过的不再压缩
imagemin(mode === 'production'),
],
css: {
postcss: {
plugins: [
// autoprefixer({
// // 指定目标浏览器
// overrideBrowserslist: ['> 1%', 'last 2 versions'],
// }),
],
},
},
resolve: {
alias: {
'@': path.join(process.cwd(), './src'),
'@img': path.join(process.cwd(), './src/static/images'),
},
},
server: {
host: '0.0.0.0',
hmr: true,
port: Number.parseInt(env.VITE_APP_PORT, 10),
},
build: {
target: 'es2015',
minify: 'terser',
terserOptions: {
compress: {
drop_console: env.VITE_DELETE_CONSOLE === 'true',
drop_debugger: env.VITE_DELETE_CONSOLE === 'true',
},
},
// 解决windows系统对微信小程序自动关闭服务的问题
watch:
process.platform === 'win32' // 检测是否为 windows 系统
? {
exclude: ['node_modules/**', '/__uno.css'],
}
: null,
},
})
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!