第一次提交

This commit is contained in:
2026-06-03 14:18:28 +08:00
parent 6c304749b0
commit 1f1581321c
51 changed files with 4385 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
# 依赖相关 (npm/yarn)
node_modules/
package-lock.json
yarn.lock
# 编译/构建产物
dist/
# Docker 相关
.docker-compose/
# 编辑器/IDE 配置
.idea/
.vscode/
*.suo
*.ntvs*
*.njsproj
*.sln
# 脚本/可执行文件
*.sh
fpx.bat
# 压缩包
*.zip
*.rar
*.7z
*.tar
# 环境配置文件 (核心:忽略所有环境文件)
.env
.env.development
.env.production
.env.line
.env.outnet
.env.test
# 其他临时文件
*.env
+5
View File
@@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}
Vendored
+12
View File
@@ -0,0 +1,12 @@
/// <reference types="vite/client" />
// 声明你的环境变量,按需添加
interface ImportMetaEnv {
readonly VITE_BASE_PATH: string
// 继续添加你项目里其他 VITE_ 开头变量
// readonly VITE_ROUTER_MODE: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="/favicon.ico">
<title>%VITE_TITLE%</title>
</head>
<body>
<noscript>
<strong>We're sorry but %VITE_TITLE% doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<!-- built files will be auto injected -->
</body>
</html>
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./",
"moduleResolution": "node",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}
+37
View File
@@ -0,0 +1,37 @@
{
"name": "work-show-web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"autoprefixer": "^10.5.0",
"axios": "^1.16.1",
"core-js": "^3.8.3",
"element-plus": "^2.14.1",
"postcss": "^8.5.15",
"vue": "^3.2.13",
"vue-router": "^4.0.3",
"vue-waterfall-plugin-next": "^3.0.1",
"vue3-waterfall-plugin": "^1.1.5",
"vuex": "^4.0.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.7",
"@vue/cli-plugin-typescript": "^5.0.9",
"sass": "^1.32.7",
"sass-loader": "^12.0.0",
"tailwindcss": "3",
"typescript": "^6.0.3",
"vite": "^8.0.15"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: [
require('tailwindcss'),
require('autoprefixer')
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

+26
View File
@@ -0,0 +1,26 @@
<template>
<router-view />
</template>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
+7
View File
@@ -0,0 +1,7 @@
import request from "./request";
import works from "./works";
interface ApiInterface {
key: Function;
}
const apis: ApiInterface = Object.assign({}, works(request));
export default apis;
+153
View File
@@ -0,0 +1,153 @@
import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
AxiosError,
} from "axios";
import { showMsg } from "@/utils/showMsg";
import {showLoading,hiddenLoading} from "@/utils/loading";
// 定义响应数据结构
interface ResponseData<T = any> {
code: number;
data: T;
message?: string;
}
// 定义配置扩展接口
interface CustomAxiosRequestConfig extends AxiosRequestConfig {
donNotShowLoading?: boolean;
}
// 创建axios实例
const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_BASE_PATH,
timeout: 1000 * 10 * 60, // 原有超时配置(600秒)
});
// ========== 新增:辅助函数 - 判断是否为无网络状态 ==========
const isOffline = () => {
// 浏览器原生API,判断当前是否处于离线状态
return typeof window !== "undefined" && !window.navigator.onLine;
};
// 请求拦截器(保留原有业务逻辑,无修改)
service.interceptors.request.use(
(config: any) => {
const { method } = config;
if (method === "get" && config.params) {
config.data = config.params;
}
config.headers = {
"Content-Type": "application/json",
// [import.meta.env.VITE_SESS_KEY]: `Bearer ${userStore.token}`,
...config.headers,
};
return config;
},
(error: AxiosError) => {
const config = error.config as CustomAxiosRequestConfig;
showMsg(error.message || "请求错误", "error");
return Promise.reject(error);
}
);
// 响应拦截器(新增:超时 + 无网络判断)
service.interceptors.response.use(
async (response: AxiosResponse<ResponseData>) => {
const { data, headers } = response;
// 处理zip文件响应
if (headers["content-type"] === "application/zip") {
return data;
}
// 处理Blob响应
if (data instanceof Blob) {
return data;
}
let { code, data: obj, message } = data;
if (code === 200) {
hiddenLoading();
// showMsg("请求成功", "success");
if (headers.message) {
message = decodeURI(headers.message);
}
return obj;
} else {
message && showMsg(message || decodeURI(headers.message), "error");
hiddenLoading();
return Promise.reject(data);
}
},
async (error: AxiosError) => {
let { message, response, config: requestConfig } = error;
let config = requestConfig as CustomAxiosRequestConfig;
console.log("接口报错", response, error.code);
// ========== 新增核心1:超时错误判断(Axios错误码 ECONNABORTED ==========
const isTimeout = error.code === AxiosError.ECONNABORTED;
// ========== 新增核心2:无网络判断(结合原生API + 无response ==========
const noNetwork = isOffline();
// 无响应的场景(超时 / 无网络 / 其他网络异常)
if (!response) {
// 区分提示:无网络 > 超时 > 通用网络异常
if (noNetwork) {
message = "当前无网络连接,请检查网络后重试";
} else if (isTimeout) {
message = "请求超时,服务器响应过慢,请稍后重试";
} else {
message = "网络异常,请检查网络设置";
}
showMsg(message, "error");
hiddenLoading();
return Promise.reject(error);
}
// 有响应但状态码错误的场景(保留原有逻辑)
let { status, data } = response;
if (data) {
data?.message && (message = data.message);
data?.code && (error.code = data.code);
}
switch (status) {
case 401:
// showMsg.confirm({
// title: "登录过期",
// message: message || "登录过期",
// confirmButtonText: "重新登录",
// cancelButtonText: "取消",
// showCancelButton: false,
// closeOnPopstate: false,
// closeOnClickOverlay: false,
// });
break;
case 404:
// await showMsg.confirm({
// title: "请求失败",
// message: message || "请求失败,状态码:404",
// confirmButtonText: "我知道了",
// showCancelButton: false,
// });
break;
case 500:
showMsg(message || `服务器错误`);
break;
default:
// ========== 新增:默认状态码也补充无网络/超时提示(兜底) ==========
if (noNetwork) {
message = "当前无网络连接,请检查网络后重试";
} else if (isTimeout) {
message = "请求超时,服务器响应过慢,请稍后重试";
}
showMsg(message || `请求失败,状态码:${status}`);
}
hiddenLoading();
return Promise.reject(error);
}
);
export default service;
+25
View File
@@ -0,0 +1,25 @@
export default ({ request }) => ({
// 作品集详情
WOEKS_LIST_ONE(params) {
return request({
url: `/public/page/product`,
method: "get",
params,
});
},
WOEKS_LIST_TWO(params) {
return request({
url: `/public/page/task/finish`,
method: "get",
params,
});
},
/* 根据类型获取字典列表 */
GET_DICT_LIST(type, params = {}) {
return request({
url: `/common/dict/select/${type}`,
method: 'get',
params
})
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

+1
View File
@@ -0,0 +1 @@
import "../styles/css/global.scss"
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+9
View File
@@ -0,0 +1,9 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index.js'
import store from './store/index.js'
import 'element-plus/dist/index.css'
import ElementPlus from 'element-plus'
import './assets/index.js'
// import 'tailwindcss/tailwind.css'
createApp(App).use(store).use(router).use(ElementPlus).mount('#app')
+25
View File
@@ -0,0 +1,25 @@
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
// {
// path: '/',
// name: 'index',
// component: () => import(/* webpackChunkName: "index" */ '../views/index.vue')
// },
// {
// path: '/detail/:taskId',
// name: 'detail',
// component: () => import(/* webpackChunkName: "works-detail" */ '../views/detail.vue')
// }
{
path: '/',
name: 'detail',
component: () => import(/* webpackChunkName: "index" */ '../views/detail.vue')
},
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
+14
View File
@@ -0,0 +1,14 @@
import { createStore } from 'vuex'
export default createStore({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
+69
View File
@@ -0,0 +1,69 @@
.text-overflow-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* // 文字溢出多行 */
.text-overflow-multi-line {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
* {
/* // text-shadow: 4px 4px 4px rgb(230, 6, 6); */
}
/* 美化滚动条 */
::-webkit-scrollbar {
width: 4px;
}
::-webkit-scrollbar-thumb {
background: #000000ad;
border-radius: 4px;
cursor: pointer;
/* // &:hover {
// background: #252525;
// } */
}
::-webkit-scrollbar-track {
background: #c1c1c12b;
border-radius: 4px;
}
.one-ell {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
.two-ell {
display: -webkit-box ;
-webkit-line-clamp: 2 ;
-webkit-box-orient: vertical ;
overflow: hidden ;
}
.three-ell {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.four-ell {
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* // *{
// color:#f00 !important;
// } */
+12
View File
@@ -0,0 +1,12 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@import "./transition.css";
@import "./reset.css";
@import "./iconfont.css";
@import "./common.css";
html,
body,
#app {
min-height: 100vh;
}
+1
View File
@@ -0,0 +1 @@
@import url(//at.alicdn.com/t/c/font_5111335_mdz5ib2itiq.css);
+384
View File
@@ -0,0 +1,384 @@
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box; /* 1 */
border-width: 0; /* 2 */
border-style: solid; /* 2 */
border-color: currentColor; /* 2 */
/* word-break: keep-all; */
word-break: break-all;
/* text-align: left; */
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
*/
html {
line-height: 1.5; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
-moz-tab-size: 4; /* 3 */
tab-size: 4; /* 3 */
font-family:
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
"Helvetica Neue",
Arial,
"Noto Sans",
sans-serif,
"Apple Color Emoji",
"Segoe UI Emoji",
"Segoe UI Symbol",
"Noto Color Emoji"; /* 4 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0; /* 1 */
line-height: inherit; /* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0; /* 1 */
color: inherit; /* 2 */
border-top-width: 1px; /* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", "Courier New", monospace; /* 1 */
font-size: 1em; /* 2 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0; /* 1 */
border-color: inherit; /* 2 */
border-collapse: collapse; /* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: inherit; /* 1 */
color: inherit; /* 1 */
margin: 0; /* 2 */
padding: 0; /* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button; /* 1 */
/* background-color: transparent; 2 */
background-image: none; /* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::placeholder,
textarea::placeholder {
opacity: 1; /* 1 */
color: #9ca3af; /* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block; /* 1 */
vertical-align: middle; /* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/*
Ensure the default browser behavior of the `hidden` attribute.
*/
[hidden] {
display: none;
}
.dark {
color-scheme: dark;
}
+82
View File
@@ -0,0 +1,82 @@
/* fade */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease-in-out;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
/* fade-slide */
.fade-slide-leave-active,
.fade-slide-enter-active {
transition: all 0.3s;
}
.fade-slide-enter-from {
opacity: 0;
transform: translateX(-30px);
}
.fade-slide-leave-to {
opacity: 0;
transform: translateX(30px);
}
/* fade-bottom */
.fade-bottom-enter-active,
.fade-bottom-leave-active {
transition:
opacity 0.25s,
transform 0.3s;
}
.fade-bottom-enter-from {
opacity: 0;
transform: translateY(-10%);
}
.fade-bottom-leave-to {
opacity: 0;
transform: translateY(10%);
}
/* fade-scale */
.fade-scale-leave-active,
.fade-scale-enter-active {
transition: all 0.28s;
}
.fade-scale-enter-from {
opacity: 0;
transform: scale(1.2);
}
.fade-scale-leave-to {
opacity: 0;
transform: scale(0.8);
}
/* zoom-fade */
.zoom-fade-enter-active,
.zoom-fade-leave-active {
transition:
transform 0.2s,
opacity 0.3s ease-out;
}
.zoom-fade-enter-from {
opacity: 0;
transform: scale(0.92);
}
.zoom-fade-leave-to {
opacity: 0;
transform: scale(1.06);
}
/* zoom-out */
.zoom-out-enter-active,
.zoom-out-leave-active {
transition:
opacity 0.1s ease-in-out,
transform 0.15s ease-out;
}
.zoom-out-enter-from,
.zoom-out-leave-to {
opacity: 0;
transform: scale(0);
}
+79
View File
@@ -0,0 +1,79 @@
/* Menu */
declare namespace Menu {
interface MenuOptions {
path: string;
name: string;
component?: string | (() => Promise<unknown>);
redirect?: string;
meta: MetaProps;
children?: MenuOptions[];
}
interface MetaProps {
icon: string;
title: string;
activeMenu?: string;
isLink?: string;
isHide: boolean;
isFull: boolean;
isAffix: boolean;
isKeepAlive: boolean;
}
}
/* FileType */
declare namespace File {
type ImageMimeType =
| "image/apng"
| "image/bmp"
| "image/gif"
| "image/jpeg"
| "image/pjpeg"
| "image/png"
| "image/svg+xml"
| "image/tiff"
| "image/webp"
| "image/x-icon";
type ExcelMimeType = "application/vnd.ms-excel" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
/* Vite */
declare type Recordable<T = any> = Record<string, T>;
declare interface ViteEnv {
VITE_USER_NODE_ENV: "development" | "production" | "test";
VITE_GLOB_APP_TITLE: string;
VITE_PORT: number;
VITE_OPEN: boolean;
VITE_REPORT: boolean;
VITE_ROUTER_MODE: "hash" | "history";
VITE_BUILD_COMPRESS: "gzip" | "brotli" | "gzip,brotli" | "none";
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE: boolean;
VITE_DROP_CONSOLE: boolean;
VITE_PWA: boolean;
VITE_DEVTOOLS: boolean;
VITE_PUBLIC_PATH: string;
VITE_API_URL: string;
VITE_BASE_PATH: string;
VITE_PROXY: [string, string, string][];
VITE_CODEINSPECTOR: boolean;
}
interface ImportMetaEnv extends ViteEnv {
__: unknown;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
/* __APP_INFO__ */
declare const __APP_INFO__: {
pkg: {
name: string;
version: string;
dependencies: Recordable<string>;
devDependencies: Recordable<string>;
};
lastBuildTime: string;
};
+17
View File
@@ -0,0 +1,17 @@
type ObjToKeyValUnion<T> = {
[K in keyof T]: { key: K; value: T[K] };
}[keyof T];
type ObjToKeyValArray<T> = {
[K in keyof T]: [K, T[K]];
}[keyof T];
type ObjToSelectedValueUnion<T> = {
[K in keyof T]: T[K];
}[keyof T];
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type GetOptional<T> = {
[P in keyof T as T[P] extends Required<T>[P] ? never : P]: T[P];
};
+8
View File
@@ -0,0 +1,8 @@
declare global {
interface Navigator {
msSaveOrOpenBlob: (blob: Blob, fileName: string) => void;
browserLanguage: string;
}
}
export {};
+45
View File
@@ -0,0 +1,45 @@
/** src/types/work.ts 瀑布流全局类型 */
export enum MediaType {
IMAGE = 1, // 纯图片
IMAGE_TEXT = 2,// 图文
VIDEO = 3, // 视频
TEXT = 4 // 纯文字
}
export interface WaterfallItem {
avatar?: string;
nickName?: string;
fileUrl?: string;
content?: string;
fileError?: boolean;
_isNew?: boolean;
_avatarLoaded?: boolean;
_mediaLoaded?: boolean;
// 动态索引签名(允许 item[字段名] 取值)
[key: string]: any;
}
export interface WaterfallProps {
list?: WaterfallItem[];
columns?: number|string;
columnGap?: number|string;
cardGap?: number|string;
imageField?: string;
titleField?: string;
descField?: string;
placeholderImage?: string;
type?: MediaType;
hasSlot?: boolean;
}
export interface TaskInfo {
title: string;
[key: string]: any;
}
export interface DictOption {
label: string;
value: number | string;
[key: string]: any;
}
+320
View File
@@ -0,0 +1,320 @@
<template>
<!-- <div v-if="taskInfo && taskTypes.length"> -->
<div class="task-production-detail">
<div
class="task-production-detail-header p-4 mb-4"
style="
display: flex;
align-items: center;
gap: 10px;
justify-content: space-between;
"
>
<div style="display: flex; align-items: center">
<p @click="goBack" class="flex items-center font-bold mr-4 cursor-pointer">
<el-icon size="16"><ArrowLeft /></el-icon>
返回
</p>
<el-tag :type="taskInfo.typeObj?.listClass" effect="dark" size="small">{{
taskInfo.typeLabel
}}</el-tag>
<h2 class="text-xl font-bold">{{ taskInfo.title }}</h2>
</div>
<el-button type="primary" size="small" text @click="refresh" :icon="Refresh">
刷新
</el-button>
</div>
<!-- 滚动容器 ref 绑定 -->
<div
ref="scrollContainer"
class="card-scroll-container px-4"
v-if="list && list.length"
>
<WaterfallFlow
:list="list"
:type="currentTaskType"
@item-click="handleCardClick"
@copy="handleCopy"
/>
<!-- 加载状态提示 -->
<div class="loading-tip">
<span v-if="isLoading">加载中...</span>
<span v-else-if="!hasMore">没有更多了</span>
</div>
</div>
<el-empty
v-else
style="height: calc(100vh - 60px)"
description="没有更多了"
/>
</div>
<!-- Vue3 移除 .sync 修饰符改为 v-model:visible -->
<el-drawer
v-model="visible"
:size="500"
:title="taskInfo.title"
@close="handleClose"
>
<div v-if="currentItem" class="detail-content">
<img
v-if="[MediaType.IMAGE, MediaType.IMAGE_TEXT].includes(currentTaskType)"
:src="currentItem.fileUrl"
@error="handleImageError"
/>
<video
v-if="[MediaType.VIDEO].includes(currentTaskType)"
:src="currentItem.fileUrl"
controls
/>
<p
v-if="[MediaType.IMAGE_TEXT, MediaType.TEXT].includes(currentTaskType)"
class="text-md mt-4 align-left"
style="text-align: left;"
>
<el-button type="text" @click.stop="handleCopy(currentItem.content)" class="!p-0" size="small">
复制文案
</el-button>
{{ currentItem.content }}
</p>
</div>
</el-drawer>
<!-- </div> -->
</template>
<script setup lang="ts">
import {
ref,
reactive,
onMounted,
onBeforeUnmount,
nextTick,
computed,
} from "vue";
import { useRoute } from "vue-router";
// Element Plus 图标 + 组件
import { ElIcon } from "element-plus";
import { Refresh, ArrowLeft } from "@element-plus/icons-vue";
// 接口请求
import apis from "@/api/index";
// 子组件
import WaterfallFlow from "./waterfallFlow.vue";
// import DictTag from "@/components/DictTag/index.vue";
// 静态资源 & 工具函数
import {
DictOption,
TaskInfo,
WaterfallItem,
// MediaType,
WaterfallProps,
} from "@/typings/work";
import defaultImg from "@/assets/images/img-load-err.png";
import fallbackCopyToClipboard from "@/utils/copyText";
enum MediaType {
IMAGE = 1, // 纯图片
IMAGE_TEXT = 2, // 图文
VIDEO = 3, // 视频
TEXT = 4, // 纯文字
}
const { WOEKS_LIST_TWO } = apis;
// ===================== 1. 路由实例(Vue3 替代 this.$route =====================
const route = useRoute();
const taskId = route.params.taskId as string;
// 复用枚举:1图片 2图文 3视频 4文字
// ===================== 2. TS 类型定义 =====================
/** 任务基础信息 */
// ===================== 3. 全局响应式数据 =====================
// 字典类型列表
const taskTypes = ref<DictOption[]>(
JSON.parse(sessionStorage.getItem("task_type") || "[]")
);
// 任务详情
const taskInfo = ref<TaskInfo>(
JSON.parse(sessionStorage.getItem("currentTask") || "{}")
);
const currentTaskType = computed(() => Number(taskInfo.value.type));
// 瀑布流列表
const list = ref<WaterfallItem[]>([]);
// 抽屉显隐
const visible = ref(false);
// 当前选中的卡片项
const currentItem = ref<WaterfallItem | null>(null);
// 分页 & 加载状态
const currentPage = ref(1);
const pageSize = ref(20);
const isLoading = ref(false);
const hasMore = ref(true);
// 滚动容器 DOM 引用(标注 TS 类型)
const scrollContainer = ref<HTMLDivElement | null>(null);
// ===================== 4. 工具/业务方法 =====================
/** 返回上一页 */
const goBack = () => {
sessionStorage.clear();
window.history.go(-1);
};
/** 刷新列表 */
const refresh = () => {
currentPage.value = 1;
list.value = [];
hasMore.value = true;
getTaskProductionListLimit();
};
/** 图片加载错误兜底 */
const handleImageError = (e: Event) => {
const target = e.target as HTMLImageElement;
target.src = defaultImg;
};
/** 分页加载作品列表(无限滚动核心) */
const getTaskProductionListLimit = async () => {
// 防重复请求
if (isLoading.value || !hasMore.value) return;
isLoading.value = true;
try {
const size = currentPage.value === 1 ? 50 : pageSize.value;
const res = await WOEKS_LIST_TWO({
taskId,
current: currentPage.value,
size,
});
const { records = [] } = res || {};
// 追加数据(而非替换)
list.value = list.value.concat(
records
// .map((item) => ({ ...item, taskInfo }))
);
// 判断是否还有更多数据
hasMore.value = records.length >= pageSize.value;
} catch (error) {
console.error("列表加载失败:", error);
// 加载失败,页码回退
currentPage.value = Math.max(1, currentPage.value - 1);
} finally {
isLoading.value = false;
}
};
/** 滚动触底加载 */
const handleScroll = () => {
const container = scrollContainer.value;
if (!container || isLoading.value || !hasMore.value) return;
const { scrollHeight, scrollTop, clientHeight } = container;
// 距离底部 50px 预加载
if (scrollTop + clientHeight >= scrollHeight - 50) {
currentPage.value++;
getTaskProductionListLimit();
}
};
/** 瀑布流卡片点击 */
const handleCardClick = (item: WaterfallItem) => {
visible.value = true;
currentItem.value = item;
console.log("点击作品:", item);
};
/** 抽屉关闭 */
const handleClose = () => {
visible.value = false;
currentItem.value = null;
};
/** 复制文案 */
const handleCopy = (text: string) => {
fallbackCopyToClipboard(text);
};
// ===================== 5. 生命周期 =====================
/** 组件挂载:初始化所有数据 + 绑定滚动事件 */
onMounted(async () => {
// 纯文字类型,修改每页条数
if (currentTaskType.value === MediaType.TEXT) {
pageSize.value = 50;
}
// 重置分页 + 加载第一页
currentPage.value = 1;
list.value = [];
hasMore.value = true;
await getTaskProductionListLimit();
// 绑定滚动事件
await nextTick();
const container = scrollContainer.value;
if (container) {
container.addEventListener("scroll", handleScroll);
}
});
/** 组件卸载:解绑滚动事件,防止内存泄漏 */
onBeforeUnmount(() => {
const container = scrollContainer.value;
if (container) {
container.removeEventListener("scroll", handleScroll);
}
});
</script>
<style scoped lang="scss">
.task-production-detail {
background-color: #fff;
border-radius: 8px;
// padding: 10px;
// box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
padding-top: 0;
.task-production-detail-header {
overflow-y: auto;
// border-bottom: 1px solid #e5e5e5;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.card-scroll-container {
max-height: calc(100vh - 60px);
overflow-y: auto;
}
}
.loading-tip {
text-align: center;
padding: 0 0 20px;
font-size: 14px;
color: #999;
}
.detail-content {
h3 {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
text-align: center;
}
img,
video {
width: 100%;
height: auto;
display: block;
object-fit: contain;
transition: transform 0.3s ease;
}
}
/* Vue3 推荐使用 :deep() 替代 ::v-deep,两种都兼容 */
:deep(.el-drawer__title) {
margin-bottom: 0 !important;
}
</style>
+564
View File
@@ -0,0 +1,564 @@
<template>
<!-- <div v-if="taskInfo && taskTypes.length"> -->
<div class="task-production-detail">
<!-- <div
class="task-production-detail-header p-4 mb-4"
style="
display: flex;
align-items: center;
gap: 10px;
justify-content: space-between;
"
>
<div style="display: flex; align-items: center">
<p @click="goBack" class="flex items-center font-bold mr-4 cursor-pointer">
<el-icon size="16"><ArrowLeft /></el-icon>
返回
</p>
<el-tag :type="taskInfo.typeObj?.listClass" effect="dark" size="small">{{
taskInfo.typeLabel
}}</el-tag>
<h2 class="text-xl font-bold">{{ taskInfo.title }}</h2>
</div>
<el-button type="primary" size="small" text @click="refresh" :icon="Refresh">
刷新
</el-button>
</div> -->
<div
class="task-production-detail-header p-4 flex items-center justify-between"
:class="[isMobile ? 'mb-4 pl-1' : 'mb-4']"
>
<p
class="text-white font-bold one-ell"
:class="[isMobile ? 'm-0 text-sm' : 'text-2xl ml-4']"
>
作品集
</p>
<div class="flex items-center gap-2 bg-[#b3d5ff] rounded-lg flex-1">
<el-input
v-model="searchForm.title"
placeholder="请输入作品标题搜索对应作品"
clearable
@input="debouncedSearch"
/>
<el-icon
@click="search"
class="text-[#0074FE] font-bold"
:class="[isMobile ? 'mr-2 text-lg' : 'mr-4 ml-2 text-2xl']"
><Search
/></el-icon>
</div>
</div>
<!-- 滚动容器 ref 绑定 -->
<div
ref="scrollContainer"
class="card-scroll-container"
:class="[isMobile ? '' : 'px-4']"
v-show="list && list.length"
>
<WaterfallFlow
:list="list"
:type="currentTaskType"
has-slot
@item-click="handleCardClick"
@copy="handleCopy"
>
<!-- <template #default="{ item }"> -->
<!-- <el-image :src="item.fileUrl" /> -->
<!-- <img :src="item.fileUrl" class="w-full object-contain rounded-md" /> -->
<!-- </template> -->
</WaterfallFlow>
<!-- 加载状态提示 -->
<div class="loading-tip">
<span v-if="isLoading">加载中...</span>
<span v-else-if="!hasMore">没有更多了</span>
</div>
</div>
<el-empty
v-show="!list || !list.length"
style="height: calc(100vh - 80px)"
description="没有更多了"
/>
</div>
<!-- Vue3 移除 .sync 修饰符改为 v-model:visible -->
<el-drawer
v-if="!isMobile"
v-model="visible"
:size="500"
@close="handleClose"
fullscreen
>
<div v-if="currentItem" class="detail-content">
<img
v-if="[MediaType.IMAGE, MediaType.IMAGE_TEXT].includes(currentTaskType)"
:src="currentItem.fileUrl"
@error="handleImageError"
/>
<video
v-if="[MediaType.VIDEO].includes(currentTaskType)"
:src="currentItem.fileUrl"
controls
/>
<p
v-if="[MediaType.IMAGE_TEXT, MediaType.TEXT].includes(currentTaskType)"
class="text-md mt-4 align-left"
>
<el-button
type="text"
@click.stop="handleCopy(currentItem.content)"
class="!p-0"
size="small"
>
复制文案
</el-button>
{{ currentItem.content }}
</p>
</div>
<template #footer>
<el-button type="info" plain @click="handleClose">关闭</el-button>
<!-- <el-button type="primary" @click="handleCopy(currentItem.content)">复制文案</el-button> -->
<!-- 保存 -->
<!-- <el-button type="primary" @click="handleSave">保存</el-button> -->
</template>
</el-drawer>
<!-- 在手机上查看大图 -->
<el-dialog
v-if="isMobile"
v-model="visible"
:size="500"
@close="handleClose"
fullscreen
>
<img
:src="currentItem.fileUrl"
class="h-[80vh] object-contain rounded-md mx-auto"
/>
<template #footer>
<el-button type="info" plain @click="handleClose">关闭</el-button>
<!-- <el-button type="primary" @click="handleCopy(currentItem.content)">复制文案</el-button> -->
<!-- 保存 -->
<!-- <el-button type="primary" @click="handleSave">保存</el-button> -->
</template>
</el-dialog>
<!-- </div> -->
</template>
<script setup lang="ts">
import {
ref,
reactive,
onMounted,
onBeforeUnmount,
nextTick,
computed,
} from "vue";
import { useRoute } from "vue-router";
import { debounce, throttle } from "lodash-es"; // 记得安装lodash-es
import { showLoading, hiddenLoading } from "@/utils/loading";
import { showMsg } from "@/utils/showMsg";
// Element Plus 图标 + 组件
import { Refresh, ArrowLeft, Search } from "@element-plus/icons-vue";
// 接口请求
import apis from "@/api/index";
// 子组件
import WaterfallFlow from "./waterfallFlow.vue";
// import DictTag from "@/components/DictTag/index.vue";
// 静态资源 & 工具函数
import {
DictOption,
TaskInfo,
WaterfallItem,
// MediaType,
WaterfallProps,
} from "@/typings/work";
import defaultImg from "@/assets/images/img-load-err.png";
import fallbackCopyToClipboard from "@/utils/copyText";
enum MediaType {
IMAGE = 1, // 纯图片
IMAGE_TEXT = 2, // 图文
VIDEO = 3, // 视频
TEXT = 4, // 纯文字
}
const searchForm = ref({
title: "",
// type: 1, //默认图片
});
const search = async () => {
currentPage.value = 1;
list.value = [];
hasMore.value = true;
scrollContainer.value.scrollTop = 0;
await getTaskProductionListLimit();
};
const debouncedSearch = debounce(search, 300);
const { WOEKS_LIST_TWO } = apis;
// ===================== 1. 路由实例(Vue3 替代 this.$route =====================
const route = useRoute();
const taskId = route.params.taskId as string;
// 复用枚举:1图片 2图文 3视频 4文字
// ===================== 2. TS 类型定义 =====================
/** 任务基础信息 */
// ===================== 3. 全局响应式数据 =====================
// 字典类型列表
const taskTypes = ref<DictOption[]>(
JSON.parse(sessionStorage.getItem("task_type") || "[]")
);
// 任务详情
const taskInfo = ref<TaskInfo>(
JSON.parse(sessionStorage.getItem("currentTask") || "{}")
);
const currentTaskType = computed(() => Number(taskInfo.value.type || 1));
// 瀑布流列表
const list = ref<WaterfallItem[]>([]);
// 抽屉显隐
const visible = ref(false);
// 当前选中的卡片项
const currentItem = ref<WaterfallItem | null>(null);
// 分页 & 加载状态
const currentPage = ref(1);
const pageSize = ref(20);
const isLoading = ref(false);
const hasMore = ref(true);
// 滚动容器 DOM 引用(标注 TS 类型)
const scrollContainer = ref<HTMLDivElement | null>(null);
// ===================== 4. 工具/业务方法 =====================
/** 返回上一页 */
const goBack = () => {
sessionStorage.clear();
window.history.go(-1);
};
/** 刷新列表 */
const refresh = () => {
currentPage.value = 1;
list.value = [];
hasMore.value = true;
getTaskProductionListLimit();
};
/** 图片加载错误兜底 */
const handleImageError = (e: Event) => {
const target = e.target as HTMLImageElement;
target.src = defaultImg;
};
/** 分页加载作品列表(无限滚动核心) */
const getTaskProductionListLimit = async () => {
// 防重复请求
if (isLoading.value || !hasMore.value) return;
isLoading.value = true;
try {
showLoading();
const size =
currentPage.value === 1
? Number(`${isMobile.value ? 20 : 50}`)
: pageSize.value;
const res = await WOEKS_LIST_TWO({
// taskId,
current: currentPage.value,
size,
...searchForm.value,
});
const { records = [] } = res || {};
// 追加数据(而非替换)
list.value = list.value.concat(
records
// .map((item) => ({ ...item, taskInfo }))
);
// 判断是否还有更多数据
hasMore.value = records.length >= pageSize.value;
} catch (error) {
console.error("列表加载失败:", error);
// 加载失败,页码回退
currentPage.value = Math.max(1, currentPage.value - 1);
} finally {
isLoading.value = false;
hiddenLoading();
}
};
/** 滚动触底加载 */
const handleScroll = throttle(() => {
const container = scrollContainer.value;
if (!container || isLoading.value || !hasMore.value) return;
const { scrollHeight, scrollTop, clientHeight } = container;
// 距离底部 50px 预加载
if (scrollTop + clientHeight >= scrollHeight - 50) {
currentPage.value++;
getTaskProductionListLimit();
}
}, 100);
// 检测师手机端还是pc端,不要宽度判断,用userAgent判断
const isMobile = computed(() => {
return navigator.userAgent.includes("Mobile");
});
/** 瀑布流卡片点击 */
const handleCardClick = (item: WaterfallItem) => {
// if (isMobile.value) {
// } else {
visible.value = true;
currentItem.value = item;
console.log("点击作品:", item);
// }
};
const saving = ref(false);
/** 抽屉关闭 */
const handleClose = () => {
visible.value = false;
// currentItem.value = null;
};
/**
* ✅ 纯前端保存功能(无后端接口)
* 支持:图片/视频/纯文字三种类型
*/
const handleSave = async () => {
if (!currentItem.value) {
ElMessage.warning("请先选择要保存的作品");
return;
}
if (saving.value) return; // 防止重复点击
saving.value = true;
try {
const item = currentItem.value;
// 生成文件名:标题_时间戳.后缀(避免重复)
const timestamp = Date.now();
const safeTitle =
item.title?.replace(/[<>:"/\\|?*]/g, "_") || `work_${item.id}`;
switch (currentTaskType.value) {
// 图片类型:Canvas转Blob下载(解决跨域问题)
case MediaType.IMAGE:
case MediaType.IMAGE_TEXT:
await saveImage(item.fileUrl, `${safeTitle}_${timestamp}.png`);
break;
// 视频类型:Fetch获取Blob下载
case MediaType.VIDEO:
await saveVideo(item.fileUrl, `${safeTitle}_${timestamp}.mp4`);
break;
// 纯文字类型:生成TXT文件下载
case MediaType.TEXT:
saveText(item.content, `${safeTitle}_${timestamp}.txt`);
break;
default:
ElMessage.warning("不支持的文件类型");
break;
}
ElMessage.success("保存成功!");
handleClose();
} catch (error) {
console.error("保存失败:", error);
ElMessage.error(error.message || "保存失败,请检查网络连接或稍后重试");
} finally {
saving.value = false;
}
};
/**
* 保存图片(解决跨域问题)
* @param url 图片URL
* @param fileName 保存的文件名
*/
const saveImage = (url: string, fileName: string): Promise<void> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous"; // 关键:允许跨域
img.onload = () => {
try {
// 创建Canvas
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
if (!ctx) {
reject(new Error("Canvas不支持"));
return;
}
// 绘制图片
ctx.drawImage(img, 0, 0);
// 转Blob并下载
canvas.toBlob((blob) => {
if (!blob) {
reject(new Error("图片转换失败"));
return;
}
downloadBlob(blob, fileName);
resolve();
}, "image/png");
} catch (e) {
reject(new Error("图片处理失败,可能是跨域限制"));
}
};
img.onerror = () => {
reject(new Error("图片加载失败"));
};
img.src = url;
});
};
/**
* 保存视频
* @param url 视频URL
* @param fileName 保存的文件名
*/
const saveVideo = async (url: string, fileName: string): Promise<void> => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`视频加载失败:${response.status}`);
}
const blob = await response.blob();
downloadBlob(blob, fileName);
} catch (error) {
throw new Error("视频下载失败,可能是文件过大或网络问题");
}
};
/**
* 保存纯文字为TXT文件
* @param text 文字内容
* @param fileName 保存的文件名
*/
const saveText = (text: string, fileName: string) => {
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
downloadBlob(blob, fileName);
};
/**
* 通用Blob下载方法
* @param blob 要下载的Blob对象
* @param fileName 保存的文件名
*/
const downloadBlob = (blob: Blob, fileName: string) => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); // 释放内存
};
/** 复制文案 */
const handleCopy = (text: string) => {
fallbackCopyToClipboard(text);
};
// ===================== 5. 生命周期 =====================
/** 组件挂载:初始化所有数据 + 绑定滚动事件 */
onMounted(async () => {
// 纯文字类型,修改每页条数
if (currentTaskType.value === MediaType.TEXT) {
pageSize.value = 50;
}
// 重置分页 + 加载第一页
currentPage.value = 1;
list.value = [];
hasMore.value = true;
await getTaskProductionListLimit();
// 绑定滚动事件
await nextTick();
const container = scrollContainer.value;
if (container) {
container.addEventListener("scroll", handleScroll);
}
});
/** 组件卸载:解绑滚动事件,防止内存泄漏 */
onBeforeUnmount(() => {
const container = scrollContainer.value;
if (container) {
container.removeEventListener("scroll", handleScroll);
}
});
</script>
<style scoped lang="scss">
.task-production-detail {
background-color: #fff;
// border-radius: 8px;
// padding: 10px;
// box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
padding-top: 0;
max-height: 100vh;
overflow: hidden;
.task-production-detail-header {
overflow-y: auto;
background-color: #0072fed6;
// border-bottom: 1px solid #e5e5e5;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
// text-align: center;
// background-color: #0072fe;
> div {
max-width: 300px;
:deep(.el-input) {
// width: 100%;
flex: 1;
}
}
}
.card-scroll-container {
max-height: calc(100vh - 60px);
overflow-y: auto;
}
}
.loading-tip {
text-align: center;
padding: 0 0 20px;
font-size: 14px;
color: #999;
}
.detail-content {
h3 {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
text-align: center;
}
img,
video {
width: 100%;
height: auto;
display: block;
object-fit: contain;
transition: transform 0.3s ease;
}
}
/* Vue3 推荐使用 :deep() 替代 ::v-deep,两种都兼容 */
:deep(.el-drawer__title) {
margin-bottom: 0 !important;
}
span {
text-align: left;
}
</style>
+628
View File
@@ -0,0 +1,628 @@
<template>
<!-- <div v-if="taskInfo && taskTypes.length"> -->
<div class="task-production-detail">
<div
class="task-production-detail-header flex items-center justify-between"
:class="[isMobile ? 'p-2' : 'p-4']"
>
<p
class="text-white font-bold one-ell"
:class="[isMobile ? 'mr-1 text-sm' : 'text-2xl ml-4']"
>
作品集
</p>
<div class="flex items-center gap-2 bg-[#b3d5ff] rounded-lg flex-1">
<el-input
v-model="searchForm.title"
placeholder="请输入作品标题搜索对应作品"
clearable
@input="debouncedSearch"
/>
<el-icon
@click="search"
class="text-[#0074FE] font-bold"
:class="[isMobile ? 'mr-2 text-lg' : 'mr-4 ml-2 text-2xl']"
><Search
/></el-icon>
</div>
</div>
<!-- 滚动容器 ref 绑定 -->
<div
ref="scrollContainer"
class="card-scroll-container"
:class="[isMobile ? '' : 'px-4']"
v-show="list && list.length"
>
<Waterfall
:key="waterfallKey"
:list="list"
:type="currentTaskType"
imgSelector="fileUrl"
show-loading
lazyload
:breakpoints="waterfallBreakpoints"
animation-effect="fadeInUp"
>
<template #default="{ item, url }">
<div
class="border rounded-md box-shadow-md rounded-xl overflow-hidden transition-all duration-300 card-item"
style="box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08)"
@click="handleCardClick(item)"
>
<img
:src="url"
class="w-full object-cover"
loading="lazy"
:style="
item.width && item.height
? {
height: calculateHeight(item.width, item.height) + 'px',
}
: {}
"
/>
<div
class="flex gap-2 items-center justify-start"
:class="[isMobile ? 'p-2' : 'p-4']"
>
<el-tag
v-for="tag in item.tags.split(',')"
:key="tag"
size="small"
plain
round
type="info"
>{{ tag }}</el-tag
>
</div>
</div>
</template>
</Waterfall>
<!-- 加载状态提示 -->
<div class="loading-tip">
<span v-if="isLoading">加载中...</span>
<span v-else-if="!hasMore">没有更多了</span>
</div>
</div>
<el-empty
v-show="!list || !list.length"
style="height: calc(100vh - 80px)"
description="没有更多了"
/>
</div>
<el-drawer
v-if="!isMobile"
v-model="visible"
:size="500"
@close="handleClose"
fullscreen
>
<div v-if="currentItem" class="detail-content">
<img
v-if="[MediaType.IMAGE, MediaType.IMAGE_TEXT].includes(currentTaskType)"
:src="currentItem.fileUrl"
@error="handleImageError"
/>
<video
v-if="[MediaType.VIDEO].includes(currentTaskType)"
:src="currentItem.fileUrl"
controls
/>
<p
v-if="[MediaType.IMAGE_TEXT, MediaType.TEXT].includes(currentTaskType)"
class="text-md mt-4 align-left"
>
<el-button
type="text"
@click.stop="handleCopy(currentItem.content)"
class="!p-0"
size="small"
>
复制文案
</el-button>
{{ currentItem.content }}
</p>
</div>
<template #footer>
<el-button type="info" plain @click="handleClose">关闭</el-button>
<!-- <el-button type="primary" @click="handleCopy(currentItem.content)">复制文案</el-button> -->
<!-- 保存 -->
<!-- <el-button type="primary" @click="handleSave">保存</el-button> -->
</template>
</el-drawer>
<el-dialog
v-if="isMobile"
v-model="visible"
:size="500"
@close="handleClose"
fullscreen
>
<img
:src="currentItem.fileUrl"
class="h-[80vh] object-contain rounded-md mx-auto"
/>
<template #footer>
<el-button type="info" plain @click="handleClose">关闭</el-button>
<!-- <el-button type="primary" @click="handleCopy(currentItem.content)">复制文案</el-button> -->
<!-- 保存 -->
<!-- <el-button type="primary" @click="handleSave">保存</el-button> -->
</template>
</el-dialog>
<el-button
v-show="showScrollToTop"
type="primary"
@click="scrollToTop"
class="fixed bottom-4 right-4 z-10 transition-all duration-300"
:icon="ArrowUp"
circle
></el-button>
</template>
<script setup lang="ts">
import {
ref,
reactive,
onMounted,
onBeforeUnmount,
nextTick,
computed,
} from "vue";
import { useRoute } from "vue-router";
import { debounce, throttle } from "lodash-es"; // 记得安装lodash-es
import { showLoading, hiddenLoading } from "@/utils/loading";
import { showMsg } from "@/utils/showMsg";
// Element Plus 图标 + 组件
import { Refresh, ArrowLeft, Search, ArrowUp } from "@element-plus/icons-vue";
// 接口请求
import apis from "@/api/index";
// 子组件
import WaterfallFlow from "./waterfallFlow.vue";
// import DictTag from "@/components/DictTag/index.vue";
// 静态资源 & 工具函数
import {
DictOption,
TaskInfo,
WaterfallItem,
// MediaType,
WaterfallProps,
} from "@/typings/work";
import defaultImg from "@/assets/images/img-load-err.png";
import fallbackCopyToClipboard from "@/utils/copyText";
import { LazyImg, Waterfall } from "vue-waterfall-plugin-next";
import "vue-waterfall-plugin-next/dist/style.css";
enum MediaType {
IMAGE = 1, // 纯图片
IMAGE_TEXT = 2, // 图文
VIDEO = 3, // 视频
TEXT = 4, // 纯文字
}
const waterfallKey = ref(0);
// ✅ 自定义响应式断点配置
const waterfallBreakpoints = {
// 1200: { rowPerView: 4 }, // 宽度 < 1200px4列
// 900: { rowPerView: 3 }, // 宽度 < 900px3列
600: { rowPerView: 2 }, // 宽度 < 600px2列(平板横屏)
320: { rowPerView: 2 }, // 宽度 < 320px2列(所有手机竖屏)
};
const searchForm = ref({
title: "",
// type: 1, //默认图片
});
const search = async () => {
currentPage.value = 1;
hasMore.value = true;
scrollContainer.value.scrollTop = 0;
await getTaskProductionListLimit();
};
const debouncedSearch = debounce(search, 300);
const { WOEKS_LIST_TWO } = apis;
// ===================== 1. 路由实例(Vue3 替代 this.$route =====================
const route = useRoute();
const taskId = route.params.taskId as string;
// 复用枚举:1图片 2图文 3视频 4文字
// ===================== 2. TS 类型定义 =====================
/** 任务基础信息 */
// ===================== 3. 全局响应式数据 =====================
// 字典类型列表
const taskTypes = ref<DictOption[]>(
JSON.parse(sessionStorage.getItem("task_type") || "[]")
);
// 任务详情
const taskInfo = ref<TaskInfo>(
JSON.parse(sessionStorage.getItem("currentTask") || "{}")
);
const currentTaskType = computed(() => Number(taskInfo.value.type || 1));
// 瀑布流列表
const list = ref<WaterfallItem[]>([]);
// 抽屉显隐
const visible = ref(false);
// 当前选中的卡片项
const currentItem = ref<WaterfallItem | null>(null);
// 分页 & 加载状态
const currentPage = ref(1);
const pageSize = computed(() => (isMobile.value ? 20 : 50));
const isLoading = ref(false);
const hasMore = ref(true);
const cardDom = computed(
() => document.getElementsByClassName("waterfall-item")[0]
);
const cardDomWidth = computed(() => cardDom.value?.offsetWidth ?? 200);
// 计算高度方法
const calculateHeight = (width: number, height: number) => {
// console.log(11111111111111, cardDom, cardDomWidth.value, width, height);
// 16*200/9=
return (cardDomWidth.value * height) / width || 356;
};
// 滚动容器 DOM 引用(标注 TS 类型)
const scrollContainer = ref<HTMLDivElement | null>(null);
// ===================== 4. 工具/业务方法 =====================
/** 返回上一页 */
const goBack = () => {
sessionStorage.clear();
window.history.go(-1);
};
/** 返回顶部 */
const scrollToTop = () => {
scrollContainer.value?.scrollTo({
top: 0,
behavior: "smooth",
});
};
/** 刷新列表 */
const refresh = () => {
currentPage.value = 1;
list.value = [];
hasMore.value = true;
getTaskProductionListLimit();
};
/** 图片加载错误兜底 */
const handleImageError = (e: Event) => {
const target = e.target as HTMLImageElement;
target.src = defaultImg;
};
/** 分页加载作品列表(无限滚动核心) */
const getTaskProductionListLimit = async () => {
// 防重复请求
if (isLoading.value || !hasMore.value) return;
isLoading.value = true;
try {
currentPage.value == 1 && showLoading();
const res = await WOEKS_LIST_TWO({
// taskId,
current: currentPage.value,
size: pageSize.value,
...searchForm.value,
});
const { records = [] } = res || {};
records.forEach((item) => {
let sizes = [
[9, 16],
[1, 1],
[16, 9],
[3, 4],
[4, 3],
[2, 3],
[3, 2],
];
if (!item.width || !item.height) {
let size = sizes[Math.floor(Math.random() * sizes.length)];
item.width = size[0];
item.height = size[1];
}
});
if (currentPage.value == 1) {
list.value = records;
} else {
list.value = list.value.concat(records);
}
// 判断是否还有更多数据
hasMore.value = !(records.length < pageSize.value);
} catch (error) {
console.error("列表加载失败:", error);
// 加载失败,页码回退
currentPage.value = Math.max(1, currentPage.value - 1);
} finally {
isLoading.value = false;
if (currentPage.value == 1 && !isFirstLoad.value) {
hiddenLoading();
}
}
};
const showScrollToTop = ref(false);
/** 滚动触底加载 */
const handleScroll = throttle(() => {
const container = scrollContainer.value;
if (!container || isLoading.value || !hasMore.value) return;
const { scrollHeight, scrollTop, clientHeight } = container;
// 距离底部 50px 预加载
if (scrollTop + clientHeight >= scrollHeight - 50) {
currentPage.value++;
getTaskProductionListLimit();
}
if (scrollTop > 1000) {
showScrollToTop.value = true;
} else {
showScrollToTop.value = false;
}
}, 100);
// 检测师手机端还是pc端,不要宽度判断,用userAgent判断
const isMobile = computed(() => {
return navigator.userAgent.includes("Mobile");
});
/** 瀑布流卡片点击 */
const handleCardClick = (item: WaterfallItem) => {
// if (isMobile.value) {
// } else {
visible.value = true;
currentItem.value = item;
console.log("点击作品:", item);
// }
};
const saving = ref(false);
/** 抽屉关闭 */
const handleClose = () => {
visible.value = false;
// currentItem.value = null;
};
/**
* ✅ 纯前端保存功能(无后端接口)
* 支持:图片/视频/纯文字三种类型
*/
const handleSave = async () => {
if (!currentItem.value) {
showMsg("请先选择要保存的作品");
return;
}
if (saving.value) return; // 防止重复点击
saving.value = true;
try {
const item = currentItem.value;
// 生成文件名:标题_时间戳.后缀(避免重复)
const timestamp = Date.now();
const safeTitle =
item.title?.replace(/[<>:"/\\|?*]/g, "_") || `work_${item.id}`;
switch (currentTaskType.value) {
// 图片类型:Canvas转Blob下载(解决跨域问题)
case MediaType.IMAGE:
case MediaType.IMAGE_TEXT:
await saveImage(item.fileUrl, `${safeTitle}_${timestamp}.png`);
break;
// 视频类型:Fetch获取Blob下载
case MediaType.VIDEO:
await saveVideo(item.fileUrl, `${safeTitle}_${timestamp}.mp4`);
break;
// 纯文字类型:生成TXT文件下载
case MediaType.TEXT:
saveText(item.content, `${safeTitle}_${timestamp}.txt`);
break;
default:
showMsg("不支持的文件类型");
break;
}
showMsg("保存成功!", "success");
handleClose();
} catch (error) {
console.error("保存失败:", error);
showMsg(error.message || "保存失败,请检查网络连接或稍后重试", "error");
} finally {
saving.value = false;
}
};
/**
* 保存图片(解决跨域问题)
* @param url 图片URL
* @param fileName 保存的文件名
*/
const saveImage = (url: string, fileName: string): Promise<void> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous"; // 关键:允许跨域
img.onload = () => {
try {
// 创建Canvas
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
if (!ctx) {
reject(new Error("Canvas不支持"));
return;
}
// 绘制图片
ctx.drawImage(img, 0, 0);
// 转Blob并下载
canvas.toBlob((blob) => {
if (!blob) {
reject(new Error("图片转换失败"));
return;
}
downloadBlob(blob, fileName);
resolve();
}, "image/png");
} catch (e) {
reject(new Error("图片处理失败,可能是跨域限制"));
}
};
img.onerror = () => {
reject(new Error("图片加载失败"));
};
img.src = url;
});
};
/**
* 保存视频
* @param url 视频URL
* @param fileName 保存的文件名
*/
const saveVideo = async (url: string, fileName: string): Promise<void> => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`视频加载失败:${response.status}`);
}
const blob = await response.blob();
downloadBlob(blob, fileName);
} catch (error) {
throw new Error("视频下载失败,可能是文件过大或网络问题");
}
};
/**
* 保存纯文字为TXT文件
* @param text 文字内容
* @param fileName 保存的文件名
*/
const saveText = (text: string, fileName: string) => {
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
downloadBlob(blob, fileName);
};
/**
* 通用Blob下载方法
* @param blob 要下载的Blob对象
* @param fileName 保存的文件名
*/
const downloadBlob = (blob: Blob, fileName: string) => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); // 释放内存
};
/** 复制文案 */
const handleCopy = (text: string) => {
fallbackCopyToClipboard(text);
};
// 是否首次加载
const isFirstLoad = ref(true);
// ===================== 5. 生命周期 =====================
/** 组件挂载:初始化所有数据 + 绑定滚动事件 */
onMounted(async () => {
// 纯文字类型,修改每页条数
// 重置分页 + 加载第一页
currentPage.value = 1;
hasMore.value = true;
await getTaskProductionListLimit();
// 绑定滚动事件
await nextTick();
const container = scrollContainer.value;
if (container) {
container.addEventListener("scroll", handleScroll);
}
setTimeout(() => {
isFirstLoad.value = false;
waterfallKey.value++;
hiddenLoading();
}, 500);
});
/** 组件卸载:解绑滚动事件,防止内存泄漏 */
onBeforeUnmount(() => {
const container = scrollContainer.value;
if (container) {
container.removeEventListener("scroll", handleScroll);
}
});
</script>
<style scoped lang="scss">
.task-production-detail {
max-height: 100vh;
overflow: hidden;
.task-production-detail-header {
overflow-y: auto;
background-color: #0072fed6;
// border-bottom: 1px solid #e5e5e5;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
// text-align: center;
// background-color: #0072fe;
> div {
max-width: 300px;
:deep(.el-input) {
// width: 100%;
flex: 1;
}
}
}
.card-scroll-container {
max-height: calc(100vh - 60px);
overflow-y: auto;
}
}
.loading-tip {
text-align: center;
padding: 0 0 20px;
font-size: 14px;
color: #999;
}
.detail-content {
h3 {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
text-align: center;
}
img,
video {
width: 100%;
height: auto;
display: block;
object-fit: contain;
transition: transform 0.3s ease;
}
}
/* Vue3 推荐使用 :deep() 替代 ::v-deep,两种都兼容 */
:deep(.el-drawer__title) {
margin-bottom: 0 !important;
}
span {
text-align: left;
}
.card-item {
&:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.829);
}
img {
&:hover {
transform: scale(1.05);
transition: transform 0.3s ease;
}
}
}
</style>
+382
View File
@@ -0,0 +1,382 @@
<template>
<div class="index-container w-[70%] mx-auto h-[100vh] flex flex-col">
<ul class="search-form flex items-center flex-wrap gap-4 mt-10 mb-5">
<li>
<span>任务标题</span>
<el-input
v-model="searchForm.title"
size="small"
placeholder="请输入任务标题"
clearable
@input="debouncedSearch"
/>
</li>
<li>
<span>任务等级</span>
<el-select
v-model="searchForm.grade"
size="small"
placeholder="请选择任务等级"
clearable
@change="debouncedSearch"
>
<el-option
v-for="item in task_user_grade"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</li>
<li>
<span>任务类型</span>
<el-select
v-model="searchForm.type"
size="small"
placeholder="请选择任务类型"
clearable
@change="debouncedSearch"
>
<el-option
v-for="item in task_type"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</li>
<li class="w-[150px] flex items-center justify-end">
<el-button type="default" size="small" @click="refresh" :icon="Refresh"
>重置</el-button
>
<el-button
type="primary"
size="small"
@click="search"
:icon="Search"
class="!ml-1"
>搜索</el-button
>
</li>
</ul>
<div
ref="scrollContainer"
class="overflow-y-auto flex-1"
v-show="list && list.length"
>
<waterfallFlow :list="list" columns="4">
<template #default="{ item }">
<div class="w-full h-full p-2 item">
<img
v-if="item.fileUrl"
:src="item.fileUrl"
alt=""
class="w-full object-contain rounded-md"
/>
<div class="flex items-start">
<el-tag :type="item.typeObj?.listClass" size="small">{{
item.typeLabel
}}</el-tag>
<p class="one-ell text-xl font-bold">{{ item.title }}</p>
</div>
<div class="flex gap-1 items-center">
<p
v-for="tag in item.tagView"
:key="tag"
class="text-[#0074FE] text-sm"
>
#{{ tag }}
</p>
</div>
<div
class="align-left text-[#666] text-md"
>
{{ item.describes }}
</div>
<div
class="flex item-between w-full"
style="justify-content: space-between"
>
<div class="flex items-center gap-1">
<img
v-for="i in item.grade > 5 ? 5 : item.grade"
:key="i"
src="@/assets/images/start.png"
alt=""
class="w-4 h-4"
/>
</div>
<el-button type="primary" size="small" @click="handleGo(item)"
>前往&nbsp;</el-button
>
</div>
</div>
</template>
</waterfallFlow>
<!-- 加载状态提示 -->
<div class="loading-tip text-[#ccc] text-xl w-full">
<div
v-if="isLoading"
class="flex items-center gap-2 w-full justify-center"
>
<el-icon size="20" class="animate-spin"><Loading /></el-icon>
<p>加载中...</p>
</div>
<p v-else-if="!hasMore">没有更多了</p>
</div>
</div>
<!-- <el-empty class="flex-1" v-else description="没有更多了" /> -->
<el-empty
class="flex-1"
v-if="!isLoading && !list.length"
description="暂无任务数据"
/>
</div>
</template>
<script setup>
import {
onMounted,
reactive,
ref,
nextTick,
onBeforeUnmount,
computed,
} from "vue";
import { useRouter } from "vue-router";
import { Refresh, Search, Loading } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import apis from "@/api/index";
import waterfallFlow from "./waterfallFlow.vue";
import { showLoading, hiddenLoading } from "@/utils/loading";
import { debounce, throttle } from "lodash-es"; // 记得安装lodash-es
const { WOEKS_LIST_ONE, GET_DICT_LIST } = apis;
const router = useRouter();
const task_user_grade = ref([]);
const task_type = ref([]);
const searchForm = ref({
title: "",
grade: "",
type: "",
});
const list = ref([]);
const pageSize = 20;
const currentPage = ref(1);
const isLoading = ref(false);
const hasMore = ref(true);
// ✅ 修复9:请求取消控制器
let abortController = null;
/** 刷新列表 */
const refresh = () => {
searchForm.value = {
title: "",
grade: "",
type: "",
};
search();
};
const search = async () => {
scrollContainer.value.scrollTop = 0;
// 取消之前未完成的请求
if (abortController) {
abortController.abort();
}
currentPage.value = 1;
hasMore.value = true;
list.value = [];
await getTaskProductionListLimit();
};
// ✅ 修复7:搜索防抖300ms
const debouncedSearch = debounce(search, 300);
/** 分页加载作品列表(无限滚动核心) */
const getTaskProductionListLimit = async () => {
if (isLoading.value || !hasMore.value) return;
isLoading.value = true;
abortController = new AbortController();
try {
showLoading();
const currentSize = currentPage.value === 1 ? 50 : pageSize;
const res = await WOEKS_LIST_ONE(
{
...searchForm.value,
current: currentPage.value,
size: currentSize,
},
{ signal: abortController.signal }
);
const { records = [] } = res || {};
const newList = handleContent(records);
if (currentPage.value === 1) {
list.value = newList;
} else {
list.value = list.value.concat(newList);
}
// 滚动到顶部
// ✅ 修复5:根据当前页的实际请求大小判断是否有更多
hasMore.value = records.length >= currentSize;
} catch (error) {
// 忽略主动取消的请求
if (error.name !== "AbortError") {
console.error("列表加载失败:", error);
ElMessage.error("列表加载失败,请稍后重试");
// ✅ 修复4:加载失败不回退页码,避免无限循环
}
} finally {
isLoading.value = false;
hiddenLoading();
abortController = null;
}
};
const scrollContainer = ref(null);
/** 滚动触底加载 */
// ✅ 修复8:滚动节流100ms
const handleScroll = throttle(() => {
const container = scrollContainer.value;
if (!container || isLoading.value || !hasMore.value) return;
const { scrollHeight, scrollTop, clientHeight } = container;
// 距离底部100px预加载,提高体验
if (scrollTop + clientHeight >= scrollHeight - 100) {
currentPage.value++;
getTaskProductionListLimit();
}
}, 100);
const getDictList = async () => {
try {
showLoading();
// ✅ 修复11:先从缓存读取字典数据
const cachedGrade = sessionStorage.getItem("task_user_grade");
if (cachedGrade) {
task_user_grade.value = JSON.parse(cachedGrade);
} else {
const res1 = await GET_DICT_LIST("task_user_grade");
task_user_grade.value = res1;
sessionStorage.setItem("task_user_grade", JSON.stringify(res1));
}
const cachedType = sessionStorage.getItem("task_type");
if (cachedType) {
task_type.value = JSON.parse(cachedType);
} else {
const res2 = await GET_DICT_LIST("task_type");
task_type.value = res2;
sessionStorage.setItem("task_type", JSON.stringify(res2));
}
} catch (error) {
console.error("字典加载失败:", error);
ElMessage.error("字典数据加载失败");
} finally {
hiddenLoading();
}
};
// 处理内容
const handleContent = (arr) =>
arr.map((task) => {
const { type, tags } = task;
const typeObj = task_type.value.find((item) => item.value == type);
// ✅ 修复3:tags空值保护和过滤
let tagView = [];
if (tags && typeof tags === "string") {
tagView = tags.split(",").filter((tag) => tag.trim() !== "");
}
return {
...task,
typeLabel: typeObj?.label,
typeObj,
tagView,
};
});
const handleGo = (item) => {
// 建议:不要用sessionStorage存储,直接通过路由传id,详情页自己请求
sessionStorage.setItem("currentTask", JSON.stringify(item));
router.push(`/detail/${item.id}`);
};
// ✅ 修复6:图片加载事件,触发瀑布流重排
const handleImageLoad = () => {
// column-count瀑布流浏览器会自动重排,这里不需要额外操作
// 如果你用的是JS计算位置的瀑布流,这里需要调用重排方法
};
const handleImageError = (e) => {
const target = e.target;
target.src = "@/assets/images/img-load-err.png"; // 替换成你的默认错误图
};
onMounted(async () => {
await getDictList();
await search();
// 绑定滚动事件(容器永远存在,不会绑定失败)
await nextTick();
const container = scrollContainer.value;
if (container) {
container.addEventListener("scroll", handleScroll);
}
});
onBeforeUnmount(() => {
// 取消未完成的请求
if (abortController) {
abortController.abort();
}
// 移除滚动事件
const container = scrollContainer.value;
if (container) {
container.removeEventListener("scroll", handleScroll);
}
// 清除防抖节流定时器
debouncedSearch.cancel();
handleScroll.cancel();
});
</script>
<style scoped lang="scss">
.index-container {
}
.search-form {
li {
display: flex;
align-items: center;
gap: 5px;
> span {
min-width: 50px;
}
::v-deep {
.el-input,
.el-select {
width: 180px;
}
}
}
}
.item {
> img,
> div {
margin-bottom: 10px;
&:last-child {
margin-bottom: 0;
}
}
}
</style>
+387
View File
@@ -0,0 +1,387 @@
<template>
<div class="waterfall-container" :style="containerStyle">
<div
class="waterfall-card mb-4"
v-for="(item, index) in list"
:key="index"
:class="{ 'new-card': item._isNew }"
@click="handleClick(item)"
>
<slot :item="item">
<!-- 用户头部兼容无头像 -->
<div
class="card-header"
style="
display: flex;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ddd;
"
v-if="false"
>
<!-- v-if="item.avatar || item.nickName" -->
<img
:src="item.avatar || defaultAvatar"
alt=""
class="mr-2 w-[30px] h-[30px] rounded-full"
@load="handleAvatarLoad($event, item)"
@error="handleAvatarError($event, item)"
/>
<span class="one-ell">{{ item.nickName || "未知用户" }}</span>
<el-button
v-if="item[descField as keyof WaterfallItem]"
type="text"
size="small"
@click.stop="handleCopy(item[descField as keyof WaterfallItem] as string)"
class="!p-0"
>复制文案</el-button
>
</div>
<!-- 图片区域 -->
<div class="card-image" v-if="type != MediaType.TEXT">
<img
v-if="[MediaType.IMAGE, MediaType.IMAGE_TEXT].includes(type)"
:src="item[imageField as keyof WaterfallItem]"
:key="item[imageField as keyof WaterfallItem]"
@load="handleImageLoad($event, item)"
@error="handleImageError($event, item)"
loading="lazy"
fit="cover"
/>
<video
v-if="[MediaType.VIDEO].includes(type)"
:src="item[imageField as keyof WaterfallItem]"
loading="lazy"
@loadedmetadata="handleVideoLoad(item)"
@error="handleVideoError(item)"
/>
</div>
<!-- 文字区域 -->
<div class="card-content" v-if="item[descField as keyof WaterfallItem]">
<p
v-if="[MediaType.IMAGE_TEXT, MediaType.TEXT].includes(type)"
class="card-desc"
:style="type !== MediaType.TEXT ? { '-webkit-line-clamp': 3 } : {}"
>
{{ item[descField as keyof WaterfallItem] }}
</p>
</div>
<div class="flex gap-2 items-center justify-start p-4">
<el-tag v-for="tag in item.tags.split(',')" :key="tag" size="small" plain round type="info">{{
tag
}}</el-tag>
</div>
</slot>
</div>
</div>
</template>
<script setup lang="ts">
import {
ref,
reactive,
computed,
watch,
onBeforeUnmount,
defineProps,
withDefaults,
defineEmits,
} from "vue";
import { showMsg } from "@/utils/showMsg";
import { showLoading, hiddenLoading } from "@/utils/loading";
// 静态资源
import defaultAvatar from "@/assets/images/profile.jpg";
import defaultImg from "@/assets/images/img-load-err.png";
import { WaterfallProps, WaterfallItem } from "@/typings/work";
enum MediaType {
IMAGE = 1,
IMAGE_TEXT = 2,
VIDEO = 3,
TEXT = 4,
}
const props = withDefaults(defineProps<WaterfallProps>(), {
list: () => [],
columns: 7,
columnGap: "16px",
cardGap: "16px",
imageField: "fileUrl",
titleField: "title",
descField: "content",
placeholderImage: defaultImg,
type: MediaType.TEXT,
hasSlot: false,
});
// ===================== 4. 定义组件触发事件 =====================
const emit = defineEmits<{
copy: [text: string];
"item-click": [item: WaterfallItem];
}>();
// ===================== 5. 响应式变量(替代原 data =====================
// 上一次列表长度,区分新旧数据
const lastListLength = ref(0);
// 卡片定时器集合:item -> 定时器ID
const cardTimers = reactive(new Map<WaterfallItem, number>());
// ===================== 6. 计算属性 =====================
/** 容器样式(列数、列间距) */
const containerStyle = computed(() => {
let { columns, columnGap, list } = props;
return {
// columnCount: list.length < 7 ? 3 : `${Number(columns)} `,
columnCount: `${Number(columns)} `,
columnGap: `${Number(columnGap)} `,
};
});
/** 图片预览地址列表 */
const previewSrcList = computed(() => {
return props.type === MediaType.IMAGE
? props.list.map((item) => item[props.imageField] as string)
: [];
});
// ===================== 7. 工具方法 =====================
/** 检查当前卡片所有资源是否加载完成 */
const checkItemLoaded = (item: WaterfallItem) => {
if (item._avatarLoaded && item._mediaLoaded && item._isNew) {
// 清除对应定时器
const timer = cardTimers.get(item);
if (timer) {
clearTimeout(timer);
cardTimers.delete(item);
}
// 显示卡片
item._isNew = false;
}
};
// ===================== 8. 业务事件方法 =====================
/** 复制文案 */
const handleCopy = (text: string) => {
emit("copy", text);
};
/** 卡片点击 */
const handleClick = (item: WaterfallItem) => {
if (item.fileError) {
showMsg("文件已损坏");
} else {
emit("item-click", item);
}
};
/** 图片加载失败 */
const handleImageError = (e: Event, item: WaterfallItem) => {
const target = e.target as HTMLImageElement;
target.src = defaultImg;
item._mediaLoaded = true;
checkItemLoaded(item);
};
/** 图片加载成功 */
const handleImageLoad = (e: Event, item: WaterfallItem) => {
item._mediaLoaded = true;
checkItemLoaded(item);
};
/** 头像加载失败 */
const handleAvatarError = (e: Event, item: WaterfallItem) => {
const target = e.target as HTMLImageElement;
target.src = defaultAvatar;
item._avatarLoaded = true;
checkItemLoaded(item);
};
/** 头像加载成功 */
const handleAvatarLoad = (e: Event, item: WaterfallItem) => {
item._avatarLoaded = true;
checkItemLoaded(item);
};
/** 视频加载失败 */
const handleVideoError = (item: WaterfallItem) => {
item.fileError = true;
item._mediaLoaded = true;
checkItemLoaded(item);
};
/** 视频加载完成 */
const handleVideoLoad = (item: WaterfallItem) => {
item._mediaLoaded = true;
checkItemLoaded(item);
};
// ===================== 9. 监听属性 =====================
/** 监听列表变化,处理新增卡片加载状态 */
watch(
() => props.list,
(newList) => {
if (props.hasSlot) {
return;
}
// showLoading();
// 只处理新增数据
const newItems = newList.slice(lastListLength.value);
newItems.forEach((item) => {
// 标记为新卡片(默认隐藏)
item._isNew = true;
// 初始化加载状态
item._avatarLoaded = !item.avatar;
item._mediaLoaded = props.type === MediaType.TEXT;
// 纯文字/无头像:直接显示
if (item._avatarLoaded && item._mediaLoaded) {
item._isNew = false;
return;
}
// 超时兜底:3秒强制显示
const timer = setTimeout(() => {
if (item._isNew) {
console.log("单个卡片加载超时,强制显示");
item._isNew = false;
// hiddenLoading();
}
cardTimers.delete(item);
}, 3000);
cardTimers.set(item, timer);
});
// 更新上次列表长度
lastListLength.value = newList.length;
},
{ immediate: true, deep: true }
);
/** 监听卡片类型切换 */
watch(
() => props.type,
(newType) => {
props.list.forEach((item) => {
item._mediaLoaded = newType === MediaType.TEXT;
checkItemLoaded(item);
});
},
{ immediate: true }
);
// ===================== 10. 生命周期:组件卸载,清除所有定时器 =====================
onBeforeUnmount(() => {
cardTimers.forEach((timer) => clearTimeout(timer));
cardTimers.clear();
});
</script>
<style lang="scss" scoped>
.waterfall-container {
width: 100%;
box-sizing: border-box;
// padding: 16px;
// padding-top: 0;
column-fill: balance;
will-change: contents;
contain: layout;
.waterfall-card {
break-inside: avoid;
page-break-inside: avoid;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
}
.waterfall-card {
background-color: #fff;
border-radius: 8px;
border: 1px solid #ddd;
overflow: hidden;
cursor: pointer;
transition: all 0.3s ease;
display: inline-block;
width: 100%;
vertical-align: top !important;
/* 新卡片默认隐藏,加载完淡入 */
&.new-card {
opacity: 0;
visibility: hidden;
}
&:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
.card-image {
width: 100%;
overflow: hidden;
img,
video {
width: 100%;
height: auto;
display: block;
object-fit: cover;
transition: transform 0.3s ease;
}
&:hover img,
&:hover video {
transform: scale(1.05);
}
}
.card-content {
padding: 12px 16px;
.card-desc {
font-size: 12px;
color: #666;
margin: 0;
line-height: 1.6;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
font-weight: 500;
word-break: break-all;
word-wrap: break-word;
}
}
}
/* 响应式适配 */
@media (max-width: 1200px) {
.waterfall-container {
column-count: 4 !important;
}
}
@media (max-width: 992px) {
.waterfall-container {
column-count: 3 !important;
}
}
@media (max-width: 768px) {
.waterfall-container {
column-count: 2 !important;
padding: 12px;
}
.waterfall-card {
margin-bottom: 12px;
}
}
@media (max-width: 480px) {
.waterfall-container {
column-count: 2 !important;
column-gap: 12px !important;
padding: 8px;
}
.waterfall-card {
margin-bottom: 12px;
}
}
</style>
+10
View File
@@ -0,0 +1,10 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{vue,js,ts,jsx,tsx}"
],
theme: {
extend: {},
},
plugins: [],
}
+30
View File
@@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* */
"moduleResolution": "bundler", // Vite 推荐 bundler
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
/* */
"baseUrl": "./",
"paths": {
"@/utils/*": ["utils/*"],
"@/*": ["src/*"]
},
/* */
"types": ["vite/client"],
"strict": false,
"esModuleInterop": true
},
"include": ["src/**/*", "src/typings/**/*", "utils/**/*"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
+59
View File
@@ -0,0 +1,59 @@
import { ElMessage } from "element-plus";
/**
* @description hex颜色转rgb颜色
* @param {String} str 颜色值字符串
* @returns {String} 返回处理后的颜色值
*/
export function hexToRgb(str: any) {
let hexs: any = "";
let reg = /^\#?[0-9A-Fa-f]{6}$/;
if (!reg.test(str)) return ElMessage.warning("输入错误的hex");
str = str.replace("#", "");
hexs = str.match(/../g);
for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexs[i], 16);
return hexs;
}
/**
* @description rgb颜色转Hex颜色
* @param {*} r 代表红色
* @param {*} g 代表绿色
* @param {*} b 代表蓝色
* @returns {String} 返回处理后的颜色值
*/
export function rgbToHex(r: any, g: any, b: any) {
let reg = /^\d{1,3}$/;
if (!reg.test(r) || !reg.test(g) || !reg.test(b)) return ElMessage.warning("输入错误的rgb颜色值");
let hexs = [r.toString(16), g.toString(16), b.toString(16)];
for (let i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`;
return `#${hexs.join("")}`;
}
/**
* @description 加深颜色值
* @param {String} color 颜色值字符串
* @param {Number} level 加深的程度,限0-1之间
* @returns {String} 返回处理后的颜色值
*/
export function getDarkColor(color: string, level: number) {
let reg = /^\#?[0-9A-Fa-f]{6}$/;
if (!reg.test(color)) return ElMessage.warning("输入错误的hex颜色值");
let rgb = hexToRgb(color);
for (let i = 0; i < 3; i++) rgb[i] = Math.round(20.5 * level + rgb[i] * (1 - level));
return rgbToHex(rgb[0], rgb[1], rgb[2]);
}
/**
* @description 变浅颜色值
* @param {String} color 颜色值字符串
* @param {Number} level 加深的程度,限0-1之间
* @returns {String} 返回处理后的颜色值
*/
export function getLightColor(color: string, level: number) {
let reg = /^\#?[0-9A-Fa-f]{6}$/;
if (!reg.test(color)) return ElMessage.warning("输入错误的hex颜色值");
let rgb = hexToRgb(color);
for (let i = 0; i < 3; i++) rgb[i] = Math.round(255 * level + rgb[i] * (1 - level));
return rgbToHex(rgb[0], rgb[1], rgb[2]);
}
+23
View File
@@ -0,0 +1,23 @@
/**一键复制 */
// import { Message } from "element-ui";
import {showMsg} from "@/utils/showMsg";
function fallbackCopyToClipboard(text) {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand("copy");
// alert('复制成功(降级方案)!');
showMsg("已复制到剪切板", "success");
} catch (err) {
console.error("降级复制失败:", err);
// alert('复制失败,请手动复制!');
showMsg("复制失败,请手动复制!", "error");
}
document.body.removeChild(textarea);
}
export default fallbackCopyToClipboard;
+95
View File
@@ -0,0 +1,95 @@
/**
* @description 时间相关工具函数
*/
/**
* 格式化日期时间为指定格式
* @param date 日期对象或字符串
* @param format 格式字符串,默认为 'YYYY-MM-DD HH:mm:ss'
* @returns 格式化后的日期时间字符串
*/
export function formatDateTime(date: Date | string | number, format: string = 'YYYY-MM-DD HH:mm:ss'): string {
if (!date) return '';
const d = new Date(date);
// 检查日期是否有效
if (isNaN(d.getTime())) return '';
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
const seconds = String(d.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', String(year))
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
/**
* 格式化 sendTime 字段,确保为 'YYYY-MM-DD HH:mm:ss' 格式
* @param sendTime sendTime 字段值
* @returns 格式化后的 sendTime 字符串
*/
export function formatSendTime(sendTime: string | Date | number): string {
if (!sendTime) return '';
// 如果已经是字符串格式,验证是否符合预期格式
if (typeof sendTime === 'string') {
// 检查是否已经是 'YYYY-MM-DD HH:mm:ss' 格式
const dateTimeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
if (dateTimeRegex.test(sendTime)) {
return sendTime;
}
// 如果是其他格式的字符串,尝试解析
const parsed = new Date(sendTime);
if (!isNaN(parsed.getTime())) {
return formatDateTime(parsed);
}
return '';
}
// 如果是 Date 对象或时间戳
return formatDateTime(sendTime);
}
/**
* 验证 sendTime 格式是否正确
* @param sendTime sendTime 字段值
* @returns 是否为有效格式
*/
export function isValidSendTime(sendTime: string): boolean {
if (!sendTime) return false;
const dateTimeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
if (!dateTimeRegex.test(sendTime)) return false;
// 进一步验证日期时间是否有效
const date = new Date(sendTime);
return !isNaN(date.getTime());
}
/**
* 获取当前时间的 sendTime 格式
* @returns 当前时间的格式化字符串
*/
export function getCurrentSendTime(): string {
return formatDateTime(new Date());
}
/**
* 将日期时间转换为 sendTime 格式(用于表单提交前的处理)
* @param dateTime 日期时间值
* @returns sendTime 格式字符串
*/
export function toSendTimeFormat(dateTime: any): string {
return formatSendTime(dateTime);
}
+17
View File
@@ -0,0 +1,17 @@
// ? 系统全局字典
/**
* @description:用户性别
*/
export const genderType = [
{ label: "男", value: 1 },
{ label: "女", value: 2 }
];
/**
* @description:用户状态
*/
export const userStatus = [
{ label: "启用", value: 1, tagType: "success" },
{ label: "禁用", value: 0, tagType: "danger" }
];
+27
View File
@@ -0,0 +1,27 @@
import { ElNotification } from "element-plus";
/**
* @description 全局代码错误捕捉
* */
const errorHandler = (error: any) => {
// 过滤 HTTP 请求错误
if (error.status || error.status == 0) return false;
let errorMap: { [key: string]: string } = {
InternalError: "Javascript引擎内部错误",
ReferenceError: "未找到对象",
TypeError: "使用了错误的类型或对象",
RangeError: "使用内置对象时,参数超范围",
SyntaxError: "语法错误",
EvalError: "错误的使用了Eval",
URIError: "URI错误"
};
let errorName = errorMap[error.name] || `错误码:${error.code}` || "未知错误";
ElNotification({
title: errorName,
message: error.message ? error.message : error,
type: "error",
duration: 3000
});
};
export default errorHandler;
+470
View File
@@ -0,0 +1,470 @@
import { isArray } from "@/utils/is";
import * as dateUtils from "@/utils/date";
const mode = import.meta.env.VITE_ROUTER_MODE;
/**
* @description 获取localStorage
* @param {String} key Storage名称
* @returns {String}
*/
export function localGet(key: string) {
const value = window.localStorage.getItem(key);
try {
return JSON.parse(window.localStorage.getItem(key) as string);
} catch (error) {
console.error(error);
return value;
}
}
/**
* @description 存储localStorage
* @param {String} key Storage名称
* @param {*} value Storage值
* @returns {void}
*/
export function localSet(key: string, value: any) {
window.localStorage.setItem(key, JSON.stringify(value));
}
/**
* @description 清除localStorage
* @param {String} key Storage名称
* @returns {void}
*/
export function localRemove(key: string) {
window.localStorage.removeItem(key);
}
/**
* @description 清除所有localStorage
* @returns {void}
*/
export function localClear() {
window.localStorage.clear();
}
/**
* @description 判断数据类型
* @param {*} val 需要判断类型的数据
* @returns {String}
*/
export function isType(val: any) {
if (val === null) return "null";
if (typeof val !== "object") return typeof val;
else return Object.prototype.toString.call(val).slice(8, -1).toLocaleLowerCase();
}
/**
* @description 生成唯一 uuid
* @returns {String}
*/
export function generateUUID() {
let uuid = "";
for (let i = 0; i < 32; i++) {
let random = (Math.random() * 16) | 0;
if (i === 8 || i === 12 || i === 16 || i === 20) uuid += "-";
uuid += (i === 12 ? 4 : i === 16 ? (random & 3) | 8 : random).toString(16);
}
return uuid;
}
/**
* 判断两个对象是否相同
* @param {Object} a 要比较的对象一
* @param {Object} b 要比较的对象二
* @returns {Boolean} 相同返回 true,反之 false
*/
export function isObjectValueEqual(a: { [key: string]: any }, b: { [key: string]: any }) {
if (!a || !b) return false;
let aProps = Object.getOwnPropertyNames(a);
let bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) return false;
for (let i = 0; i < aProps.length; i++) {
let propName = aProps[i];
let propA = a[propName];
let propB = b[propName];
if (!b.hasOwnProperty(propName)) return false;
if (propA instanceof Object) {
if (!isObjectValueEqual(propA, propB)) return false;
} else if (propA !== propB) {
return false;
}
}
return true;
}
/**
* @description 生成随机数
* @param {Number} min 最小值
* @param {Number} max 最大值
* @returns {Number}
*/
export function randomNum(min: number, max: number): number {
let num = Math.floor(Math.random() * (min - max) + max);
return num;
}
/**
* @description 获取当前时间对应的提示语
* @returns {String}
*/
export function getTimeState() {
let timeNow = new Date();
let hours = timeNow.getHours();
if (hours >= 6 && hours <= 10) return `早上好 ⛅`;
if (hours >= 10 && hours <= 14) return `中午好 🌞`;
if (hours >= 14 && hours <= 18) return `下午好 🌞`;
if (hours >= 18 && hours <= 24) return `晚上好 🌛`;
if (hours >= 0 && hours <= 6) return `凌晨好 🌛`;
}
/**
* @description 获取浏览器默认语言
* @returns {String}
*/
export function getBrowserLang() {
let browserLang = navigator.language ? navigator.language : navigator.browserLanguage;
let defaultBrowserLang = "";
if (["cn", "zh", "zh-cn"].includes(browserLang.toLowerCase())) {
defaultBrowserLang = "zh";
} else {
defaultBrowserLang = "en";
}
return defaultBrowserLang;
}
/**
* @description 获取不同路由模式所对应的 url + params
* @returns {String}
*/
export function getUrlWithParams() {
const url = {
hash: location.hash.substring(1),
history: location.pathname + location.search
};
return url[mode];
}
/**
* @description 使用递归扁平化菜单,方便添加动态路由
* @param {Array} menuList 菜单列表
* @returns {Array}
*/
export function getFlatMenuList(menuList: Menu.MenuOptions[]): Menu.MenuOptions[] {
let newMenuList: Menu.MenuOptions[] = JSON.parse(JSON.stringify(menuList));
return newMenuList.flatMap(item => [item, ...(item.children ? getFlatMenuList(item.children) : [])]);
}
/**
* @description 使用递归过滤出需要渲染在左侧菜单的列表 (需剔除 isHide == true 的菜单)
* @param {Array} menuList 菜单列表
* @returns {Array}
* */
export function getShowMenuList(menuList: Menu.MenuOptions[]) {
let newMenuList: Menu.MenuOptions[] = JSON.parse(JSON.stringify(menuList));
return newMenuList.filter(item => {
item.children?.length && (item.children = getShowMenuList(item.children));
return !item.meta?.isHide;
});
}
/**
* @description 使用递归找出所有面包屑存储到 pinia/vuex 中
* @param {Array} menuList 菜单列表
* @param {Array} parent 父级菜单
* @param {Object} result 处理后的结果
* @returns {Object}
*/
export const getAllBreadcrumbList = (menuList: Menu.MenuOptions[], parent = [], result: { [key: string]: any } = {}) => {
for (const item of menuList) {
result[item.path] = [...parent, item];
if (item.children) getAllBreadcrumbList(item.children, result[item.path], result);
}
return result;
};
/**
* @description 使用递归处理路由菜单 path,生成一维数组 (第一版本地路由鉴权会用到,该函数暂未使用)
* @param {Array} menuList 所有菜单列表
* @param {Array} menuPathArr 菜单地址的一维数组 ['**','**']
* @returns {Array}
*/
export function getMenuListPath(menuList: Menu.MenuOptions[], menuPathArr: string[] = []): string[] {
for (const item of menuList) {
if (typeof item === "object" && item.path) menuPathArr.push(item.path);
if (item.children?.length) getMenuListPath(item.children, menuPathArr);
}
return menuPathArr;
}
/**
* @description 递归查询当前 path 所对应的菜单对象 (该函数暂未使用)
* @param {Array} menuList 菜单列表
* @param {String} path 当前访问地址
* @returns {Object | null}
*/
export function findMenuByPath(menuList: Menu.MenuOptions[], path: string): Menu.MenuOptions | null {
for (const item of menuList) {
if (item.path === path) return item;
if (item.children) {
const res = findMenuByPath(item.children, path);
if (res) return res;
}
}
return null;
}
/**
* @description 使用递归过滤需要缓存的菜单 name (该函数暂未使用)
* @param {Array} menuList 所有菜单列表
* @param {Array} keepAliveNameArr 缓存的菜单 name ['**','**']
* @returns {Array}
* */
export function getKeepAliveRouterName(menuList: Menu.MenuOptions[], keepAliveNameArr: string[] = []) {
menuList.forEach(item => {
item.meta.isKeepAlive && item.name && keepAliveNameArr.push(item.name);
item.children?.length && getKeepAliveRouterName(item.children, keepAliveNameArr);
});
return keepAliveNameArr;
}
/**
* @description 格式化表格单元格默认值 (el-table-column)
* @param {Number} row 行
* @param {Number} col 列
* @param {*} callValue 当前单元格值
* @returns {String}
* */
export function formatTableColumn(row: number, col: number, callValue: any) {
// 如果当前值为数组,使用 / 拼接(根据需求自定义)
if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "--";
return callValue ?? "--";
}
/**
* @description 处理 ProTable 值为数组 || 无数据
* @param {*} callValue 需要处理的值
* @returns {String}
* */
export function formatValue(callValue: any) {
// 如果当前值为数组,使用 / 拼接(根据需求自定义)
if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "--";
return callValue ?? "--";
}
/**
* @description 处理 prop 为多级嵌套的情况,返回的数据 (列如: prop: user.name)
* @param {Object} row 当前行数据
* @param {String} prop 当前 prop
* @returns {*}
* */
export function handleRowAccordingToProp(row: { [key: string]: any }, prop: string) {
if (!prop.includes(".")) return row[prop] ?? "--";
prop.split(".").forEach(item => (row = row[item] ?? "--"));
return row;
}
/**
* @description 处理 prop,当 prop 为多级嵌套时 ==> 返回最后一级 prop
* @param {String} prop 当前 prop
* @returns {String}
* */
export function handleProp(prop: string) {
const propArr = prop.split(".");
if (propArr.length == 1) return prop;
return propArr[propArr.length - 1];
}
/**
* @description 递归查找 callValue 对应的 enum 值
* */
export function findItemNested(enumData: any, callValue: any, value: string, children: string) {
return enumData.reduce((accumulator: any, current: any) => {
if (accumulator) return accumulator;
if (current[value] === callValue) return current;
if (current[children]) return findItemNested(current[children], callValue, value, children);
}, null);
}
export function checkType(data: unknown): string {
const type = Object.prototype.toString.call(data);
return type.slice(8, -1).toLowerCase();
}
export function isEmpty(data: unknown): boolean {
const dataType = checkType(data);
switch (dataType) {
case "array":
return !(data as Array<unknown>).length;
case "object":
return !Object.keys(data as object).length;
case "map":
case "set":
return !(data as Map<unknown, unknown> | Set<unknown>).size;
case "boolean":
case "number":
case "symbol":
case "function":
return false;
default:
return !data;
}
}
import type { FilesType } from "../components/FilesCard/types.d.ts";
/* 公共 相关 开始 */
/* 公共 相关 结束 */
/* FileCard 组件相关 开始 */
// 更据文件后缀名获取文件类型
export function getFileType(fileExtension: string): {
lowerCase: FilesType;
upperCase: string;
} {
// 去除后缀名开头的点,并转换为小写
const cleanExtension = fileExtension.replace(".", "").toLowerCase();
if (!cleanExtension) {
return { lowerCase: "unknown", upperCase: "Unknown" };
}
const imageExtensions = ["png", "jpg", "jpeg", "gif", "bmp", "svg", "webp"];
const wordExtensions = ["doc", "docx"];
const excelExtensions = ["xls", "xlsx"];
const pptExtensions = ["ppt", "pptx"];
const audioExtensions = ["mp3", "wav", "ogg", "flac"];
const videoExtensions = ["mp4", "avi", "mov", "mkv"];
const codeExtensions = ["js", "ts", "html", "css", "py", "java", "c", "cpp", "json", "php"];
const databaseExtensions = ["sql", "db", "sqlite"];
const zipExtensions = ["zip", "rar", "7z"];
const markExtensions = ["md", "mdx"];
if (imageExtensions.includes(cleanExtension)) {
return { lowerCase: "image", upperCase: "Image" };
}
if (wordExtensions.includes(cleanExtension)) {
return { lowerCase: "word", upperCase: "Word" };
}
if (excelExtensions.includes(cleanExtension)) {
return { lowerCase: "excel", upperCase: "Excel" };
}
if (pptExtensions.includes(cleanExtension)) {
return { lowerCase: "ppt", upperCase: "Ppt" };
}
if (cleanExtension === "pdf") {
return { lowerCase: "pdf", upperCase: "Pdf" };
}
if (cleanExtension === "txt") {
return { lowerCase: "txt", upperCase: "Txt" };
}
if (markExtensions.includes(cleanExtension)) {
return { lowerCase: "mark", upperCase: "Markdown" };
}
if (audioExtensions.includes(cleanExtension)) {
return { lowerCase: "audio", upperCase: "Audio" };
}
if (videoExtensions.includes(cleanExtension)) {
return { lowerCase: "video", upperCase: "Video" };
}
if (codeExtensions.includes(cleanExtension)) {
return { lowerCase: "code", upperCase: "Code" };
}
if (databaseExtensions.includes(cleanExtension)) {
return { lowerCase: "database", upperCase: "Database" };
}
if (cleanExtension === "lnk") {
return { lowerCase: "link", upperCase: "Link" };
}
if (zipExtensions.includes(cleanExtension)) {
return { lowerCase: "zip", upperCase: "Zip" };
}
if (cleanExtension === "obj" || cleanExtension === "fbx" || cleanExtension === "glb") {
return { lowerCase: "three", upperCase: "3D" };
}
return { lowerCase: "file", upperCase: "File" };
}
// 获取文件大小
export function getSize(size: number) {
let retSize = size;
const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];
let unitIndex = 0;
while (retSize >= 1024 && unitIndex < units.length - 1) {
retSize /= 1024;
unitIndex++;
}
return `${retSize.toFixed(0)} ${units[unitIndex]}`;
}
// 通过文件流,生成图片预览
// Follow code is copy from `antd/components/upload/utils.ts`:
export function isImageFileType(type: string): boolean {
return type.indexOf("image/") === 0;
}
const MEASURE_SIZE = 200;
export function previewImage(file: File | Blob): Promise<string> {
return new Promise<string>(resolve => {
if (!file || !file.type || !isImageFileType(file.type)) {
resolve("");
return;
}
const img = new Image();
img.onload = () => {
const { width, height } = img;
const ratio = width / height;
const MEASURE_SIZE_WIDTH = ratio > 1 ? MEASURE_SIZE : MEASURE_SIZE * ratio;
const MEASURE_SIZE_HEIGHT = ratio > 1 ? MEASURE_SIZE / ratio : MEASURE_SIZE;
const canvas = document.createElement("canvas");
canvas.width = MEASURE_SIZE_WIDTH;
canvas.height = MEASURE_SIZE_HEIGHT;
canvas.style.cssText = `position: fixed; left: 0; top: 0; width: ${MEASURE_SIZE_WIDTH}px; height: ${MEASURE_SIZE_HEIGHT}px; z-index: 9999; display: none;`;
document.body.appendChild<HTMLCanvasElement>(canvas);
const ctx = canvas.getContext("2d");
ctx!.drawImage(img, 0, 0, MEASURE_SIZE_WIDTH, MEASURE_SIZE_HEIGHT);
const dataURL = canvas.toDataURL();
document.body.removeChild(canvas);
window.URL.revokeObjectURL(img.src);
resolve(dataURL);
};
img.crossOrigin = "anonymous";
if (file.type.startsWith("image/svg+xml")) {
const reader = new FileReader();
reader.onload = () => {
if (reader.result && typeof reader.result === "string") {
img.src = reader.result;
}
};
reader.readAsDataURL(file);
} else if (file.type.startsWith("image/gif")) {
const reader = new FileReader();
reader.onload = () => {
if (reader.result) {
resolve(reader.result as string);
}
};
reader.readAsDataURL(file);
} else {
img.src = window.URL.createObjectURL(file);
}
});
}
/* FileCard 组件相关 结束 */
/* 日期时间工具函数 开始 */
export const {
formatDateTime,
formatSendTime,
isValidSendTime,
getCurrentSendTime,
toSendTimeFormat
} = dateUtils;
/* 日期时间工具函数 结束 */
+125
View File
@@ -0,0 +1,125 @@
/**
* @description: 判断值是否未某个类型
*/
export function is(val: unknown, type: string) {
return Object.prototype.toString.call(val) === `[object ${type}]`;
}
/**
* @description: 是否为函数
*/
export function isFunction<T = Function>(val: unknown): val is T {
return is(val, "Function");
}
/**
* @description: 是否已定义
*/
export const isDef = <T = unknown>(val?: T): val is T => {
return typeof val !== "undefined";
};
/**
* @description: 是否未定义
*/
export const isUnDef = <T = unknown>(val?: T): val is T => {
return !isDef(val);
};
/**
* @description: 是否为对象
*/
export const isObject = (val: any): val is Record<any, any> => {
return val !== null && is(val, "Object");
};
/**
* @description: 是否为时间
*/
export function isDate(val: unknown): val is Date {
return is(val, "Date");
}
/**
* @description: 是否为数值
*/
export function isNumber(val: unknown): val is number {
return is(val, "Number");
}
/**
* @description: 是否为AsyncFunction
*/
export function isAsyncFunction<T = any>(val: unknown): val is Promise<T> {
return is(val, "AsyncFunction");
}
/**
* @description: 是否为promise
*/
export function isPromise<T = any>(val: unknown): val is Promise<T> {
return is(val, "Promise") && isObject(val) && isFunction(val.then) && isFunction(val.catch);
}
/**
* @description: 是否为字符串
*/
export function isString(val: unknown): val is string {
return is(val, "String");
}
/**
* @description: 是否为boolean类型
*/
export function isBoolean(val: unknown): val is boolean {
return is(val, "Boolean");
}
/**
* @description: 是否为数组
*/
export function isArray(val: any): val is Array<any> {
return val && Array.isArray(val);
}
/**
* @description: 是否客户端
*/
export const isClient = () => {
return typeof window !== "undefined";
};
/**
* @description: 是否为浏览器
*/
export const isWindow = (val: any): val is Window => {
return typeof window !== "undefined" && is(val, "Window");
};
/**
* @description: 是否为 element 元素
*/
export const isElement = (val: unknown): val is Element => {
return isObject(val) && !!val.tagName;
};
/**
* @description: 是否为 null
*/
export function isNull(val: unknown): val is null {
return val === null;
}
/**
* @description: 是否为 null || undefined
*/
export function isNullOrUnDef(val: unknown): val is null | undefined {
return isUnDef(val) || isNull(val);
}
/**
* @description: 是否为 16 进制颜色
*/
export const isHexColor = (str: string) => {
return /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(str);
};
+30
View File
@@ -0,0 +1,30 @@
import { ElLoading } from "element-plus";
const loadingStack = [];
const showLoading = (text='数据加载中...') => {
const loadingInstance = ElLoading.service({
lock: true,
text: `${text}...`,
background: "rgba(228, 228, 228, 0.57)",
});
loadingStack.push(loadingInstance);
return loadingInstance;
};
const hiddenLoading = () => {
if (loadingStack.length > 0) {
const loadingInstance = loadingStack.pop();
loadingInstance.close();
}
};
// 强制关闭所有 Loading(可选)
const hiddenAllLoading = () => {
while (loadingStack.length > 0) {
const loadingInstance = loadingStack.pop();
loadingInstance.close();
}
};
export { showLoading, hiddenLoading, hiddenAllLoading };
+13
View File
@@ -0,0 +1,13 @@
// 显示错误
import { ElNotification } from "element-plus";
export function showMsg(t: string, type = "error", isCatch = true, reason?: string, duration = 2000) {
ElNotification({
title: t,
type,
duration
});
if (isCatch && type != "success") {
throw Error(reason || t);
}
// if (isCatch && type != 'success') { return reason || t; }
}
+13
View File
@@ -0,0 +1,13 @@
/**
* @description Loading Svg
*/
export const loadingSvg = `
<path class="path" d="
M 30 15
L 28 17
M 25.61 25.61
A 15 15, 0, 0, 1, 15 30
A 15 15, 0, 1, 1, 27.99 7.5
L 15 15
" style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
`;
+3
View File
@@ -0,0 +1,3 @@
export const toBeian = () => {
window.open("https://beian.miit.gov.cn/", "_blank");
};
+25
View File
@@ -0,0 +1,25 @@
import type { Ref } from "vue";
import { computed } from "vue";
export default function useFileNameParser(name: Ref<string | undefined>) {
const namePrefix = computed(() => {
const nameStr = name.value || "";
const lastDotIndex = nameStr.lastIndexOf(".");
return lastDotIndex === -1 ? nameStr : nameStr.slice(0, lastDotIndex);
});
const nameSuffix = computed(() => {
const nameStr = name.value || "";
const lastDotIndex = nameStr.lastIndexOf(".");
if (lastDotIndex === -1 && nameStr.length - lastDotIndex > 10) {
// 文件名长度超过10个字符 显示.file
return ".file";
}
return lastDotIndex === -1 ? "" : nameStr.slice(lastDotIndex);
});
return {
namePrefix,
nameSuffix
};
}
+56
View File
@@ -0,0 +1,56 @@
import { defineConfig, ConfigEnv, loadEnv } from 'vite'
// import {
// getRootPath,
// getSrcPath,
// setupVitePlugins,
// } from "./build";
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { fileURLToPath, URL } from 'url'
// https://vitejs.dev/config/
export default defineConfig((configEnv: ConfigEnv) => {
const viteEnv = loadEnv(
configEnv.mode,
process.cwd()
) as unknown as ImportMetaEnv;
return {
plugins: [vue()],
// plugins: setupVitePlugins(viteEnv),
// 1. 路径别名(对应你之前的 @ -> src
resolve: {
alias: {
'@/utils': path.resolve(__dirname, './utils'),
"~": path.resolve(__dirname, './src'),
'@': path.resolve(__dirname, './src'),
'@/typings': path.resolve(__dirname, './src/typings'),
components: path.resolve(__dirname, "components"),
},
extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
},
// 2. SCSS 兼容 & 全局变量(和 Vue CLI 写法不同)
css: {
preprocessorOptions: {
scss: {
// 如果你有全局 scss 变量文件,在这里引入
// additionalData: `@use "@/assets/styles/variables.scss" as *;`
}
}
},
// 3. 开发服务配置(端口、跨域、自动打开浏览器等)
server: {
host: "0.0.0.0",
port: viteEnv.VITE_CLI_PORT,
proxy: {
[viteEnv.VITE_BASE_API]: {
target: viteEnv.VITE_BASE_PATH,
changeOrigin: true,
rewrite: (path: string) =>
path.replace(new RegExp("^" + viteEnv.VITE_BASE_API), ""),
},
},
}
}
})