first commit

This commit is contained in:
2026-06-12 12:31:35 +08:00
commit 77e9f1df50
261 changed files with 24791 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
<template>
<el-input v-model="a" @blur="amountBlur" @focus="amountFocus" :placeholder="placeholder" size="default"></el-input>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import { amountFormat } from "@/utils/format";
const props = defineProps({
modelValue: {
type: String,
default: "",
},
precision: {
type: Number,
default: 2,
},
unit: {
type: Boolean,
default: true,
},
maxlength: {
type: Number || String,
default: 10,
},
placeholder: {
type: String,
default: "请输入金额",
},
});
const emits = defineEmits(["update:modelValue"]);
let a = ref(props.modelValue + "");
let temp = "temp";
const amountFocus = function () {
a.value = temp;
temp = "temp";
};
const amountBlur = function () {
temp = a.value;
a.value = amountFormat(a.value, props.precision, props.unit);
};
amountBlur();
watch(a, (newVal, oldValue) => {
// 临时变量不为'temp'时不启动监听
if (temp !== "temp") return;
// pc端中文输入法'。' ==> '.'
let newStr = (newVal + "").replace("。", ".").replace(/[^0-9.]/g, "");
let oldStr = oldValue + "";
// .xxx ==> 0.xxx
if (newStr.startsWith(".")) {
newStr = "0." + newStr.slice(1);
}
// 0xxx ==> xxx
if (newStr.startsWith("0") && newStr.length > 1 && !newStr.slice(1).startsWith(".")) {
newStr = newStr.slice(1);
}
// 限制小数点数量、小数点后两位小数、金额字符串总长度
if (
newStr.split(".").length > 2 ||
(newStr.split(".").length == 2 && newStr.split(".")[1].length > props.precision) ||
newStr.length > Number(props.maxlength)
) {
newStr = oldStr;
}
a.value = newStr;
emits("update:modelValue", newStr);
});
</script>
+38
View File
@@ -0,0 +1,38 @@
<template>
<component :is="linkType" v-bind="linkProps(to)">
<slot></slot>
</component>
</template>
<script setup lang="ts">
defineOptions({
name: "AppLink",
inheritAttrs: false,
});
import { isExternal } from "@/utils/index";
const props = defineProps({
to: {
type: Object,
required: true,
},
});
const isExternalLink = computed(() => {
return isExternal(props.to.path || "");
});
const linkType = computed(() => (isExternalLink.value ? "a" : "router-link"));
const linkProps = (to: any) => {
if (isExternalLink.value) {
return {
href: to.path,
target: "_blank",
rel: "noopener noreferrer",
};
}
return { to: to };
};
</script>
+97
View File
@@ -0,0 +1,97 @@
<template>
<el-breadcrumb class="flex-y-center">
<transition-group
enter-active-class="animate__animated animate__fadeInRight"
>
<el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
<span
v-if="
item.redirect === 'noredirect' || index === breadcrumbs.length - 1
"
class="color-gray-400"
>{{ translateRouteTitle(item.meta.title) }}</span
>
<a v-else @click.prevent="handleLink(item)">
{{ translateRouteTitle(item.meta.title) }}
</a>
</el-breadcrumb-item>
</transition-group>
</el-breadcrumb>
</template>
<script setup lang="ts">
import { RouteLocationMatched } from "vue-router";
import { compile } from "path-to-regexp";
import router from "@/router";
import { translateRouteTitle } from "@/utils/i18n";
const currentRoute = useRoute();
const pathCompile = (path: string) => {
const { params } = currentRoute;
const toPath = compile(path);
return toPath(params);
};
const breadcrumbs = ref<Array<RouteLocationMatched>>([]);
function getBreadcrumb() {
let matched = currentRoute.matched.filter(
(item) => item.meta && item.meta.title
);
const first = matched[0];
if (!isDashboard(first)) {
matched = [
{ path: "/dashboard", meta: { title: "dashboard" } } as any,
].concat(matched);
}
breadcrumbs.value = matched.filter((item) => {
return item.meta && item.meta.title && item.meta.breadcrumb !== false;
});
}
function isDashboard(route: RouteLocationMatched) {
const name = route && route.name;
if (!name) {
return false;
}
return (
name.toString().trim().toLocaleLowerCase() ===
"Dashboard".toLocaleLowerCase()
);
}
function handleLink(item: any) {
const { redirect, path } = item;
if (redirect) {
router.push(redirect).catch((err) => {
console.warn(err);
});
return;
}
router.push(pathCompile(path)).catch((err) => {
console.warn(err);
});
}
watch(
() => currentRoute.path,
(path) => {
if (path.startsWith("/redirect/")) {
return;
}
getBreadcrumb();
}
);
onBeforeMount(() => {
getBreadcrumb();
});
</script>
<style lang="scss" scoped>
// 覆盖 element-plus 的样式
.el-breadcrumb__inner,
.el-breadcrumb__inner a {
font-weight: 400 !important;
}
</style>
File diff suppressed because it is too large Load Diff
+174
View File
@@ -0,0 +1,174 @@
<template>
<el-form
ref="formRef"
label-width="auto"
v-bind="form"
:model="formData"
:rules="formRules"
>
<el-row :gutter="20">
<template v-for="item in formItems" :key="item.prop">
<el-col v-show="!item.hidden" v-bind="item.col">
<el-form-item :label="item.label" :prop="item.prop">
<!-- Label -->
<template #label v-if="item.tips">
<span>
{{ item.label }}
<el-tooltip
placement="bottom"
effect="light"
:content="item.tips"
:raw-content="true"
>
<el-icon style="vertical-align: -0.15em" size="16">
<QuestionFilled />
</el-icon>
</el-tooltip>
</span>
</template>
<!-- Input 输入框 -->
<template v-if="item.type === 'input' || item.type === undefined">
<el-input v-model="formData[item.prop]" v-bind="item.attrs" />
</template>
<!-- Select 选择器 -->
<template v-else-if="item.type === 'select'">
<el-select v-model="formData[item.prop]" v-bind="item.attrs">
<template v-for="option in item.options" :key="option.value">
<el-option v-bind="option" />
</template>
</el-select>
</template>
<!-- Radio 单选框 -->
<template v-else-if="item.type === 'radio'">
<el-radio-group v-model="formData[item.prop]" v-bind="item.attrs">
<template v-for="option in item.options" :key="option.value">
<el-radio v-bind="option" />
</template>
</el-radio-group>
</template>
<!-- Checkbox 多选框 -->
<template v-else-if="item.type === 'checkbox'">
<el-checkbox-group
v-model="formData[item.prop]"
v-bind="item.attrs"
>
<template v-for="option in item.options" :key="option.value">
<el-checkbox v-bind="option" />
</template>
</el-checkbox-group>
</template>
<!-- Input Number 数字输入框 -->
<template v-else-if="item.type === 'input-number'">
<el-input-number
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- TreeSelect 树形选择 -->
<template v-else-if="item.type === 'tree-select'">
<el-tree-select
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- DatePicker 日期选择器 -->
<template v-else-if="item.type === 'date-picker'">
<el-date-picker
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Text 文本 -->
<template v-else-if="item.type === 'text'">
<el-text v-bind="item.attrs">{{ formData[item.prop] }}</el-text>
</template>
<!-- 自定义 -->
<template v-else-if="item.type === 'custom'">
<slot
:name="item.slotName ?? item.prop"
:prop="item.prop"
:formData="formData"
:attrs="item.attrs"
></slot>
</template>
</el-form-item>
</el-col>
</template>
</el-row>
</el-form>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch, watchEffect } from "vue";
import { IObject, IPageForm } from "./types";
// 定义接收的属性
const props = withDefaults(defineProps<IPageForm>(), {
pk: "id",
});
const formRef = ref<FormInstance>();
const formItems = reactive(props.formItems);
const formData = reactive<IObject>({});
const formRules: FormRules = {};
const prepareFuncs = [];
for (const item of formItems) {
item.initFn && item.initFn(item);
formData[item.prop] = item.initialValue ?? "";
formRules[item.prop] = item.rules ?? [];
if (item.watch !== undefined) {
prepareFuncs.push(() => {
watch(
() => formData[item.prop],
(newValue, oldValue) => {
item.watch && item.watch(newValue, oldValue, formData, formItems);
}
);
});
}
if (item.computed !== undefined) {
prepareFuncs.push(() => {
watchEffect(() => {
item.computed && (formData[item.prop] = item.computed(formData));
});
});
}
if (item.watchEffect !== undefined) {
prepareFuncs.push(() => {
watchEffect(() => {
item.watchEffect && item.watchEffect(formData);
});
});
}
}
prepareFuncs.forEach((func) => func());
// 获取表单数据
function getFormData(key?: string) {
return key === undefined ? formData : (formData[key] ?? undefined);
}
// 设置表单值
function setFormData(data: IObject) {
for (const key in formData) {
if (formData.hasOwnProperty(key) && key in data) {
formData[key] = data[key];
}
}
if (data?.hasOwnProperty(props.pk)) {
formData[props.pk] = data[props.pk];
}
}
// 设置表单项值
function setFormItemData(key: string, value: any) {
formData[key] = value;
}
// 暴露的属性和方法
defineExpose({ formRef, getFormData, setFormData, setFormItemData });
</script>
+425
View File
@@ -0,0 +1,425 @@
<template>
<!-- drawer -->
<template v-if="modalConfig.component === 'drawer'">
<el-drawer
v-model="modalVisible"
:append-to-body="true"
v-bind="modalConfig.drawer"
@close="handleCloseModal"
>
<!-- 表单 -->
<el-form
ref="formRef"
label-width="auto"
v-bind="modalConfig.form"
:model="formData"
:rules="formRules"
>
<el-row :gutter="20">
<template v-for="item in formItems" :key="item.prop">
<el-col v-show="!item.hidden" v-bind="item.col">
<el-form-item :label="item.label" :prop="item.prop">
<!-- Label -->
<template #label v-if="item.tips">
<span>
{{ item.label }}
<el-tooltip
placement="bottom"
effect="light"
:content="item.tips"
:raw-content="true"
>
<el-icon style="vertical-align: -0.15em" size="16">
<QuestionFilled />
</el-icon>
</el-tooltip>
</span>
</template>
<!-- Input 输入框 -->
<template
v-if="item.type === 'input' || item.type === undefined"
>
<el-input v-model="formData[item.prop]" v-bind="item.attrs" />
</template>
<!-- Select 选择器 -->
<template v-else-if="item.type === 'select'">
<el-select v-model="formData[item.prop]" v-bind="item.attrs">
<template
v-for="option in item.options"
:key="option.value"
>
<el-option v-bind="option" />
</template>
</el-select>
</template>
<!-- Radio 单选框 -->
<template v-else-if="item.type === 'radio'">
<el-radio-group
v-model="formData[item.prop]"
v-bind="item.attrs"
>
<template
v-for="option in item.options"
:key="option.value"
>
<el-radio v-bind="option" />
</template>
</el-radio-group>
</template>
<!-- switch 开关 -->
<template v-else-if="item.type === 'switch'">
<el-switch
inline-prompt
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Checkbox 多选框 -->
<template v-else-if="item.type === 'checkbox'">
<el-checkbox-group
v-model="formData[item.prop]"
v-bind="item.attrs"
>
<template
v-for="option in item.options"
:key="option.value"
>
<el-checkbox v-bind="option" />
</template>
</el-checkbox-group>
</template>
<!-- Input Number 数字输入框 -->
<template v-else-if="item.type === 'input-number'">
<el-input-number
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- TreeSelect 树形选择 -->
<template v-else-if="item.type === 'tree-select'">
<el-tree-select
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- DatePicker 日期选择器 -->
<template v-else-if="item.type === 'date-picker'">
<el-date-picker
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Text 文本 -->
<template v-else-if="item.type === 'text'">
<el-text v-bind="item.attrs">
{{ formData[item.prop] }}
</el-text>
</template>
<!-- 自定义 -->
<template v-else-if="item.type === 'custom'">
<slot
:name="item.slotName ?? item.prop"
:prop="item.prop"
:formData="formData"
:attrs="item.attrs"
></slot>
</template>
</el-form-item>
</el-col>
</template>
</el-row>
</el-form>
<!-- 弹窗底部操作按钮 -->
<template #footer>
<div>
<el-button type="primary" @click="handleSubmit">确 定</el-button>
<el-button @click="handleClose">取 消</el-button>
</div>
</template>
</el-drawer>
</template>
<!-- dialog -->
<template v-else>
<el-dialog
v-model="modalVisible"
:align-center="true"
:append-to-body="true"
width="70vw"
v-bind="modalConfig.dialog"
style="padding-right: 0"
@close="handleCloseModal"
>
<!-- 滚动 -->
<el-scrollbar max-height="60vh">
<!-- 表单 -->
<el-form
ref="formRef"
label-width="auto"
v-bind="modalConfig.form"
style="padding-right: var(--el-dialog-padding-primary)"
:model="formData"
:rules="formRules"
>
<el-row :gutter="20">
<template v-for="item in formItems" :key="item.prop">
<el-col v-show="!item.hidden" v-bind="item.col">
<el-form-item :label="item.label" :prop="item.prop">
<!-- Label -->
<template #label v-if="item.tips">
<span>
{{ item.label }}
<el-tooltip
placement="bottom"
effect="light"
:content="item.tips"
:raw-content="true"
>
<el-icon style="vertical-align: -0.15em" size="16">
<QuestionFilled />
</el-icon>
</el-tooltip>
</span>
</template>
<!-- Input 输入框 -->
<template
v-if="item.type === 'input' || item.type === undefined"
>
<el-input
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Select 选择器 -->
<template v-else-if="item.type === 'select'">
<el-select
v-model="formData[item.prop]"
v-bind="item.attrs"
>
<template
v-for="option in item.options"
:key="option.value"
>
<el-option v-bind="option" />
</template>
</el-select>
</template>
<!-- Radio 单选框 -->
<template v-else-if="item.type === 'radio'">
<el-radio-group
v-model="formData[item.prop]"
v-bind="item.attrs"
>
<template
v-for="option in item.options"
:key="option.value"
>
<el-radio v-bind="option" />
</template>
</el-radio-group>
</template>
<!-- switch 开关 -->
<template v-else-if="item.type === 'switch'">
<el-switch
inline-prompt
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Checkbox 多选框 -->
<template v-else-if="item.type === 'checkbox'">
<el-checkbox-group
v-model="formData[item.prop]"
v-bind="item.attrs"
>
<template
v-for="option in item.options"
:key="option.value"
>
<el-checkbox v-bind="option" />
</template>
</el-checkbox-group>
</template>
<!-- Input Number 数字输入框 -->
<template v-else-if="item.type === 'input-number'">
<el-input-number
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- TreeSelect 树形选择 -->
<template v-else-if="item.type === 'tree-select'">
<el-tree-select
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- DatePicker 日期选择器 -->
<template v-else-if="item.type === 'date-picker'">
<el-date-picker
v-model="formData[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Text 文本 -->
<template v-else-if="item.type === 'text'">
<el-text v-bind="item.attrs">
{{ formData[item.prop] }}
</el-text>
</template>
<!-- 自定义 -->
<template v-else-if="item.type === 'custom'">
<slot
:name="item.slotName ?? item.prop"
:prop="item.prop"
:formData="formData"
:attrs="item.attrs"
></slot>
</template>
</el-form-item>
</el-col>
</template>
</el-row>
</el-form>
</el-scrollbar>
<!-- 弹窗底部操作按钮 -->
<template #footer>
<div style="padding-right: var(--el-dialog-padding-primary)">
<el-button type="primary" @click="handleSubmit">确 定</el-button>
<el-button @click="handleClose">取 消</el-button>
</div>
</template>
</el-dialog>
</template>
</template>
<script setup lang="ts">
import { useThrottleFn } from "@vueuse/core";
import type { FormInstance, FormRules } from "element-plus";
import { nextTick, reactive, ref, watch, watchEffect } from "vue";
import type { IModalConfig, IObject } from "./types";
// 定义接收的属性
const props = defineProps<{
modalConfig: IModalConfig;
}>();
// 自定义事件
const emit = defineEmits<{
submitClick: [];
}>();
const pk = props.modalConfig.pk ?? "id";
const modalVisible = ref(false);
const formRef = ref<FormInstance>();
const formItems = reactive(props.modalConfig.formItems);
const formData = reactive<IObject>({});
const formRules: FormRules = {};
const prepareFuncs = [];
for (const item of formItems) {
item.initFn && item.initFn(item);
formData[item.prop] = item.initialValue ?? "";
formRules[item.prop] = item.rules ?? [];
if (item.watch !== undefined) {
prepareFuncs.push(() => {
watch(
() => formData[item.prop],
(newValue, oldValue) => {
item.watch && item.watch(newValue, oldValue, formData, formItems);
}
);
});
}
if (item.computed !== undefined) {
prepareFuncs.push(() => {
watchEffect(() => {
item.computed && (formData[item.prop] = item.computed(formData));
});
});
}
if (item.watchEffect !== undefined) {
prepareFuncs.push(() => {
watchEffect(() => {
item.watchEffect && item.watchEffect(formData);
});
});
}
}
prepareFuncs.forEach((func) => func());
// 获取表单数据
function getFormData(key?: string) {
return key === undefined ? formData : (formData[key] ?? undefined);
}
// 设置表单值
function setFormData(data: IObject) {
for (const key in formData) {
if (formData.hasOwnProperty(key) && key in data) {
formData[key] = data[key];
}
}
if (data?.hasOwnProperty(pk)) {
formData[pk] = data[pk];
}
}
// 设置表单项值
function setFormItemData(key: string, value: any) {
formData[key] = value;
}
// 显示modal
function setModalVisible(data: IObject = {}) {
modalVisible.value = true;
// nextTick解决赋值后重置表单无效问题
nextTick(() => {
Object.values(data).length > 0 && setFormData(data);
});
}
// 表单提交
const handleSubmit = useThrottleFn(() => {
formRef.value?.validate((valid: boolean) => {
if (valid) {
if (typeof props.modalConfig.beforeSubmit === "function") {
props.modalConfig.beforeSubmit(formData);
}
props.modalConfig.formAction(formData).then(() => {
let msg = "操作成功";
if (props.modalConfig.component === "drawer") {
if (props.modalConfig.drawer?.title) {
msg = `${props.modalConfig.drawer?.title}成功`;
}
} else {
if (props.modalConfig.dialog?.title) {
msg = `${props.modalConfig.dialog?.title}成功`;
}
}
ElMessage.success(msg);
emit("submitClick");
handleClose();
});
}
});
}, 3000);
// 隐藏弹窗
function handleClose() {
modalVisible.value = false;
}
// 关闭弹窗
function handleCloseModal() {
formRef.value?.resetFields();
nextTick(() => {
formRef.value?.clearValidate();
});
}
// 暴露的属性和方法
defineExpose({ setModalVisible, getFormData, setFormData, setFormItemData });
</script>
<style lang="scss" scoped></style>
+245
View File
@@ -0,0 +1,245 @@
<template>
<el-card
shadow="never"
class="mb-[10px]"
v-show="visible"
v-hasPerm="[`${searchConfig.pageName}:query`]"
>
<el-form ref="queryFormRef" :model="queryParams" :inline="true">
<template v-for="(item, index) in formItems" :key="item.prop">
<el-form-item
v-show="isExpand ? true : index < showNumber"
:label="item.label"
:prop="item.prop"
>
<!-- Label -->
<template #label v-if="item.tips">
<span>
{{ item.label }}
<el-tooltip
placement="bottom"
effect="light"
:content="item.tips"
:raw-content="true"
>
<el-icon style="vertical-align: -0.15em" size="16">
<QuestionFilled />
</el-icon>
</el-tooltip>
</span>
</template>
<!-- Input 输入框 -->
<template v-if="item.type === 'input' || item.type === undefined">
<el-input
v-model="queryParams[item.prop]"
v-bind="item.attrs"
@keyup.enter="handleQuery"
/>
</template>
<!-- InputTag 标签输入框 -->
<template v-if="item.type === 'input-tag'">
<div class="flex-center">
<el-tag
v-for="tag in inputTagMap[item.prop].data"
class="mr-2"
:key="tag"
:closable="true"
v-bind="inputTagMap[item.prop].tagAttrs"
@close="handleCloseTag(item.prop, tag)"
>
{{ tag }}
</el-tag>
<template v-if="inputTagMap[item.prop].inputVisible">
<el-input
:ref="
(el: HTMLElement) => (inputTagMap[item.prop].inputRef = el)
"
v-model="inputTagMap[item.prop].inputValue"
v-bind="inputTagMap[item.prop].inputAttrs"
@keyup.enter="handleInputConfirm(item.prop)"
@blur="handleInputConfirm(item.prop)"
/>
</template>
<template v-else>
<el-button
v-bind="inputTagMap[item.prop].buttonAttrs"
@click="handleShowInput(item.prop)"
>
{{ inputTagMap[item.prop].buttonAttrs.btnText }}
</el-button>
</template>
</div>
</template>
<!-- Select 选择器 -->
<template v-else-if="item.type === 'select'">
<el-select v-model="queryParams[item.prop]" v-bind="item.attrs">
<template v-for="option in item.options" :key="option.value">
<el-option :label="option.label" :value="option.value" />
</template>
</el-select>
</template>
<!-- TreeSelect 树形选择 -->
<template v-else-if="item.type === 'tree-select'">
<el-tree-select
v-model="queryParams[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- DatePicker 日期选择器 -->
<template v-else-if="item.type === 'date-picker'">
<el-date-picker
v-model="queryParams[item.prop]"
v-bind="item.attrs"
/>
</template>
</el-form-item>
</template>
<el-form-item>
<el-button type="primary" icon="search" @click="handleQuery">
搜索
</el-button>
<el-button icon="refresh" @click="handleReset">重置</el-button>
<!-- 展开/收起 -->
<el-link
v-if="isExpandable && formItems.length > showNumber"
class="ml-2"
type="primary"
:underline="false"
@click="isExpand = !isExpand"
>
<template v-if="isExpand">
收起
<i-ep-arrow-up />
</template>
<template v-else>
展开
<i-ep-arrow-down />
</template>
</el-link>
</el-form-item>
</el-form>
</el-card>
</template>
<script setup lang="ts">
import type { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import type { IObject, ISearchConfig } from "./types";
// 定义接收的属性
const props = defineProps<{
searchConfig: ISearchConfig;
}>();
// 自定义事件
const emit = defineEmits<{
queryClick: [queryParams: IObject];
resetClick: [queryParams: IObject];
}>();
const queryFormRef = ref<FormInstance>();
// 是否显示
const visible = ref(true);
// 响应式的formItems
const formItems = reactive(props.searchConfig.formItems);
// 是否可展开/收缩
const isExpandable = ref(props.searchConfig.isExpandable ?? true);
// 是否已展开
const isExpand = ref(false);
// 表单项展示数量,若可展开,超出展示数量的表单项隐藏
const showNumber = computed(() => {
if (isExpandable.value === true) {
return props.searchConfig.showNumber ?? 3;
} else {
return formItems.length;
}
});
// 搜索表单数据
const queryParams = reactive<IObject>({});
const inputTagMap = reactive<IObject>({});
for (const item of formItems) {
item.initFn && item.initFn(item);
if (item.type === "input-tag") {
inputTagMap[item.prop] = {
data: Array.isArray(item.initialValue) ? item.initialValue : [],
inputVisible: false,
inputValue: "",
inputRef: null,
buttonAttrs: {
size: item.attrs?.size ?? "default",
btnText: item.attrs?.btnText ?? "+ New Tag",
style: "color: #b0b2b7",
},
inputAttrs: {
size: item.attrs?.size ?? "default",
clearable: item.attrs?.clearable ?? false,
style: "width: 150px",
},
tagAttrs: {
size: item.attrs?.size ?? "default",
},
};
queryParams[item.prop] = computed({
get() {
return typeof item.attrs?.join === "string"
? inputTagMap[item.prop].data.join(item.attrs.join)
: inputTagMap[item.prop].data;
},
set(value) {
// resetFields时会被调用
inputTagMap[item.prop].data =
typeof item.attrs?.join === "string"
? value.split(item.attrs.join).filter((item: any) => item !== "")
: value;
},
});
} else {
queryParams[item.prop] = item.initialValue ?? "";
}
}
// 重置操作
function handleReset() {
queryFormRef.value?.resetFields();
emit("resetClick", queryParams);
}
// 查询操作
function handleQuery() {
emit("queryClick", queryParams);
}
// 获取分页数据
function getQueryParams() {
return queryParams;
}
// 显示/隐藏 SearchForm
function toggleVisible() {
visible.value = !visible.value;
}
// 关闭标签
function handleCloseTag(prop: string, tag: string) {
inputTagMap[prop].data.splice(inputTagMap[prop].data.indexOf(tag), 1);
}
// 添加标签
function handleInputConfirm(prop: string) {
if (inputTagMap[prop].inputValue) {
inputTagMap[prop].data.push(inputTagMap[prop].inputValue);
}
inputTagMap[prop].inputVisible = false;
inputTagMap[prop].inputValue = "";
}
// 显示标签输入框
function handleShowInput(prop: string) {
inputTagMap[prop].inputVisible = true;
nextTick(() => {
inputTagMap[prop].inputRef.focus();
});
}
// 暴露的属性和方法
defineExpose({ getQueryParams, toggleVisible });
</script>
<style lang="scss" scoped></style>
+272
View File
@@ -0,0 +1,272 @@
import type {
DialogProps,
DrawerProps,
FormItemRule,
FormProps,
PaginationProps,
TableProps,
ColProps,
} from "element-plus";
import PageContent from "./PageContent.vue";
import PageForm from "./PageForm.vue";
import PageModal from "./PageModal.vue";
import PageSearch from "./PageSearch.vue";
export type PageSearchInstance = InstanceType<typeof PageSearch>;
export type PageContentInstance = InstanceType<typeof PageContent>;
export type PageModalInstance = InstanceType<typeof PageModal>;
export type PageFormInstance = InstanceType<typeof PageForm>;
export type IObject = Record<string, any>;
export interface IOperatData {
name: string;
row: IObject;
column: IObject;
$index: number;
}
export interface ISearchConfig {
// 页面名称(参与组成权限标识,如sys:user:xxx)
pageName: string;
// 表单项
formItems: Array<{
// 组件类型(如input,select等)
type?: "input" | "select" | "tree-select" | "date-picker" | "input-tag";
// 标签文本
label: string;
// 标签提示
tips?: string;
// 键名
prop: string;
// 组件属性(input-tag组件支持join,btnText,size属性)
attrs?: IObject;
// 初始值
initialValue?: any;
// 可选项(适用于select组件)
options?: { label: string; value: any }[];
// 初始化数据函数扩展
initFn?: (formItem: IObject) => void;
}>;
// 是否开启展开和收缩
isExpandable?: boolean;
// 默认展示的表单项数量
showNumber?: number;
}
export interface IContentConfig<T = any> {
// 页面名称(参与组成权限标识,如sys:user:xxx)
pageName: string;
// table组件属性
table?: Omit<TableProps<any>, "data">;
// pagination组件属性
pagination?:
| boolean
| Partial<
Omit<
PaginationProps,
"v-model:page-size" | "v-model:current-page" | "total" | "currentPage"
>
>;
// 列表的网络请求函数(需返回promise)
indexAction: (queryParams: T) => Promise<any>;
// 默认的分页相关的请求参数
request?: {
pageName: string;
limitName: string;
};
// 数据格式解析的回调函数
parseData?: (res: any) => {
total: number;
list: IObject[];
[key: string]: any;
};
// 修改属性的网络请求函数(需返回promise)
modifyAction?: (data: {
[key: string]: any;
field: string;
value: boolean | string | number;
}) => Promise<any>;
// 删除的网络请求函数(需返回promise)
deleteAction?: (ids: string) => Promise<any>;
// 后端导出的网络请求函数(需返回promise)
exportAction?: (queryParams: T) => Promise<any>;
// 前端全量导出的网络请求函数(需返回promise)
exportsAction?: (queryParams: T) => Promise<IObject[]>;
// 导入模板
importTemplate?: string | (() => Promise<any>);
// 后端导入的网络请求函数(需返回promise)
importAction?: (file: File) => Promise<any>;
// 前端导入的网络请求函数(需返回promise)
importsAction?: (data: IObject[]) => Promise<any>;
// 主键名(默认为id)
pk?: string;
// 表格工具栏(默认支持add,delete,export,也可自定义)
toolbar?: Array<
| "add"
| "delete"
| "import"
| "export"
| {
auth: string;
icon?: string;
name: string;
text: string;
type?: "primary" | "success" | "warning" | "danger" | "info";
}
>;
// 表格工具栏右侧图标
defaultToolbar?: Array<
| "refresh"
| "filter"
| "imports"
| "exports"
| "search"
| {
name: string;
icon: string;
title?: string;
auth?: string;
}
>;
// table组件列属性(额外的属性templet,operat,slotName)
cols: Array<{
type?: "default" | "selection" | "index" | "expand";
label?: string;
prop?: string;
width?: string | number;
align?: "left" | "center" | "right";
columnKey?: string;
reserveSelection?: boolean;
// 列是否显示
show?: boolean;
// 模板
templet?:
| "image"
| "list"
| "url"
| "switch"
| "input"
| "price"
| "percent"
| "icon"
| "date"
| "tool"
| "custom";
// image模板相关参数
imageWidth?: number;
imageHeight?: number;
// list模板相关参数
selectList?: IObject;
// switch模板相关参数
activeValue?: boolean | string | number;
inactiveValue?: boolean | string | number;
activeText?: string;
inactiveText?: string;
// input模板相关参数
inputType?: string;
// price模板相关参数
priceFormat?: string;
// date模板相关参数
dateFormat?: string;
// tool模板相关参数
operat?: Array<
| "edit"
| "delete"
| {
auth: string;
icon?: string;
name: string;
text: string;
type?: "primary" | "success" | "warning" | "danger" | "info";
render?: (row: IObject) => boolean;
}
>;
// filter值拼接符
filterJoin?: string;
[key: string]: any;
// 初始化数据函数
initFn?: (item: IObject) => void;
}>;
}
export interface IModalConfig<T = any> {
// 页面名称
pageName?: string;
// 主键名(主要用于编辑数据,默认为id)
pk?: string;
// 组件类型
component?: "dialog" | "drawer";
// dialog组件属性
dialog?: Partial<Omit<DialogProps, "modelValue">>;
// drawer组件属性
drawer?: Partial<Omit<DrawerProps, "modelValue">>;
// form组件属性
form?: IForm;
// 表单项
formItems: IFormItems<T>;
// 提交之前处理
beforeSubmit?: (data: T) => void;
// 提交的网络请求函数(需返回promise)
formAction: (data: T) => Promise<any>;
}
export type IForm = Partial<Omit<FormProps, "model" | "rules">>;
// 表单项
export type IFormItems<T = any> = Array<{
// 组件类型(如input,select,radio,custom等,默认input)
type?:
| "input"
| "select"
| "radio"
| "switch"
| "checkbox"
| "tree-select"
| "date-picker"
| "input-number"
| "text"
| "custom";
// 组件属性
attrs?: IObject;
// 组件可选项(适用于select,radio,checkbox组件)
options?: Array<{
label: string;
value: any;
disabled?: boolean;
[key: string]: any;
}>;
// 插槽名(适用于组件类型为custom)
slotName?: string;
// 标签文本
label: string;
// 标签提示
tips?: string;
// 键名
prop: string;
// 验证规则
rules?: FormItemRule[];
// 初始值
initialValue?: any;
// 是否隐藏
hidden?: boolean;
// layout组件Col属性
col?: Partial<ColProps>;
// 监听函数
watch?: (newValue: any, oldValue: any, data: T, items: IObject[]) => void;
// 计算属性函数
computed?: (data: T) => any;
// 监听收集函数
watchEffect?: (data: T) => void;
// 初始化数据函数扩展
initFn?: (item: IObject) => void;
}>;
export interface IPageForm {
// 主键名(主要用于编辑数据,默认为id)
pk?: string;
// form组件属性
form?: IForm;
// 表单项
formItems: IFormItems;
}
+73
View File
@@ -0,0 +1,73 @@
import { ref } from "vue";
import type {
IObject,
PageContentInstance,
PageModalInstance,
PageSearchInstance,
} from "./types";
function usePage() {
const searchRef = ref<PageSearchInstance>();
const contentRef = ref<PageContentInstance>();
const addModalRef = ref<PageModalInstance>();
const editModalRef = ref<PageModalInstance>();
// 搜索
function handleQueryClick(queryParams: IObject) {
const filterParams = contentRef.value?.getFilterParams();
contentRef.value?.fetchPageData({ ...queryParams, ...filterParams }, true);
}
// 重置
function handleResetClick(queryParams: IObject) {
const filterParams = contentRef.value?.getFilterParams();
contentRef.value?.fetchPageData({ ...queryParams, ...filterParams }, true);
}
// 新增
function handleAddClick() {
//显示添加表单
addModalRef.value?.setModalVisible();
}
// 编辑
function handleEditClick(row: IObject) {
//显示编辑表单 根据数据进行填充
editModalRef.value?.setModalVisible(row);
}
// 表单提交
function handleSubmitClick() {
//根据检索条件刷新列表数据
const queryParams = searchRef.value?.getQueryParams();
contentRef.value?.fetchPageData(queryParams, true);
}
// 导出
function handleExportClick() {
// 根据检索条件导出数据
const queryParams = searchRef.value?.getQueryParams();
contentRef.value?.exportPageData(queryParams);
}
// 搜索显隐
function handleSearchClick() {
searchRef.value?.toggleVisible();
}
// 涮选数据
function handleFilterChange(filterParams: IObject) {
const queryParams = searchRef.value?.getQueryParams();
contentRef.value?.fetchPageData({ ...queryParams, ...filterParams }, true);
}
return {
searchRef,
contentRef,
addModalRef,
editModalRef,
handleQueryClick,
handleResetClick,
handleAddClick,
handleEditClick,
handleSubmitClick,
handleExportClick,
handleSearchClick,
handleFilterChange,
};
}
export default usePage;
+62
View File
@@ -0,0 +1,62 @@
<!-- 复制组件 -->
<template>
<el-button link @click="handleClipboard" :style="style">
<slot>
<el-icon><DocumentCopy color="var(--el-color-primary)" /></el-icon>
</slot>
</el-button>
</template>
<script setup lang="ts">
defineOptions({
name: "CopyButton",
inheritAttrs: false,
});
const props = defineProps({
text: {
type: String,
default: "",
},
style: {
type: Object,
default: () => ({}),
},
});
function handleClipboard() {
if (navigator.clipboard && navigator.clipboard.writeText) {
// 使用 Clipboard API
navigator.clipboard
.writeText(props.text)
.then(() => {
ElMessage.success("Copy successfully");
})
.catch((error) => {
ElMessage.warning("Copy failed");
console.log("[CopyButton] Copy failed", error);
});
} else {
// 兼容性处理(useClipboard 有兼容性问题)
const input = document.createElement("input");
input.style.position = "absolute";
input.style.left = "-9999px";
input.setAttribute("value", props.text);
document.body.appendChild(input);
input.select();
try {
const successful = document.execCommand("copy");
if (successful) {
ElMessage.success("Copy successfully!");
} else {
ElMessage.warning("Copy failed!");
}
} catch (err) {
ElMessage.error("Copy failed.");
console.log("[CopyButton] Copy failed.", err);
} finally {
document.body.removeChild(input);
}
}
}
</script>
+76
View File
@@ -0,0 +1,76 @@
<template>
<el-select
v-model="selectedValue"
:placeholder="placeholder"
:disabled="disabled"
clearable
@change="handleChange"
>
<el-option
v-for="option in options"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</template>
<script setup lang="ts">
import DictAPI from "@/api/dict";
const props = defineProps({
/**
* 字典编码(eg: 性别-gender)
*/
code: {
type: String,
required: true,
},
modelValue: {
type: [String, Number],
},
placeholder: {
type: String,
default: "请选择",
},
disabled: {
type: Boolean,
default: false,
},
});
const emits = defineEmits(["update:modelValue"]);
const options: Ref<OptionType[]> = ref([]);
const selectedValue = ref<string | number | undefined>();
watch([options, () => props.modelValue], ([newOptions, newModelValue]) => {
if (newOptions.length === 0) {
// 下拉数据源加载未完成不回显
return;
}
if (newModelValue == undefined) {
selectedValue.value = undefined;
return;
}
if (typeof newOptions[0].value === "number") {
selectedValue.value = Number(newModelValue);
} else if (typeof newOptions[0].value === "string") {
selectedValue.value = String(newModelValue);
} else {
selectedValue.value = newModelValue;
}
});
function handleChange(val?: string | number | undefined) {
emits("update:modelValue", val);
}
onBeforeMount(() => {
// 根据字典编码获取字典项
DictAPI.getOptions(props.code).then((data) => {
options.value = data;
});
});
</script>
+62
View File
@@ -0,0 +1,62 @@
<template>
<a
href="https://github.com/youlaitech"
target="_blank"
class="github-corner"
aria-label="View source on Github"
>
<svg
width="80"
height="80"
viewBox="0 0 250 250"
style="color: #fff; fill: #40c9c6"
aria-hidden="true"
>
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z" />
<path
d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
fill="currentColor"
style="transform-origin: 130px 106px"
class="octo-arm"
/>
<path
d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
fill="currentColor"
class="octo-body"
/>
</svg>
</a>
</template>
<style scoped>
.github-corner:hover .octo-arm {
animation: octocat-wave 560ms ease-in-out;
}
@keyframes octocat-wave {
0%,
100% {
transform: rotate(0);
}
20%,
60% {
transform: rotate(-25deg);
}
40%,
80% {
transform: rotate(10deg);
}
}
@media (width <= 500px) {
.github-corner .octo-arm {
animation: octocat-wave 560ms ease-in-out;
}
.github-corner:hover .octo-arm {
animation: none;
}
}
</style>
+39
View File
@@ -0,0 +1,39 @@
<template>
<div
class="px-[15px] flex items-center justify-center color-[var(--el-text-color-regular)]"
@click="toggleClick"
>
<svg-icon
class="hamburger"
:class="{ 'is-active': isActive }"
icon-class="collapse"
/>
</div>
</template>
<script setup lang="ts">
defineProps({
isActive: {
required: true,
type: Boolean,
default: false,
},
});
const emit = defineEmits(["toggleClick"]);
function toggleClick() {
emit("toggleClick");
}
</script>
<style scoped lang="scss">
.hamburger {
vertical-align: middle;
cursor: pointer;
transform: scaleX(-1);
}
.hamburger.is-active {
transform: scaleX(1);
}
</style>
+208
View File
@@ -0,0 +1,208 @@
<template>
<div ref="iconSelectRef" :style="'width:' + width">
<el-popover :visible="popoverVisible" :width="width" placement="bottom-end">
<template #reference>
<el-input
class="reference"
v-model="selectedIcon"
readonly
placeholder="点击选择图标"
@click="popoverVisible = !popoverVisible"
>
<template #prepend>
<template
v-if="selectedIcon && selectedIcon.startsWith('el-icon-')"
>
<el-icon>
<component :is="selectedIcon.replace('el-icon-', '')" />
</el-icon>
</template>
<template v-else>
<svg-icon :icon-class="selectedIcon" />
</template>
</template>
<template #suffix>
<el-icon
:style="{
transform: popoverVisible ? 'rotate(180deg)' : 'rotate(0)',
transition: 'transform .5s',
}"
@click="popoverVisible = !popoverVisible"
>
<ArrowDown />
</el-icon>
</template>
</el-input>
</template>
<!-- 下拉选择弹窗 -->
<div ref="popoverContentRef">
<el-input
v-model="searchText"
placeholder="搜索图标"
clearable
@input="filterIcons"
/>
<el-tabs v-model="activeTab" @tab-click="handleTabClick">
<el-tab-pane label="SVG 图标" name="svg">
<el-scrollbar height="300px">
<ul class="icon-container">
<li
v-for="icon in filteredSvgIcons"
:key="'svg-' + icon"
class="icon-item"
@click="selectIcon(icon)"
>
<el-tooltip :content="icon" placement="bottom" effect="light">
<svg-icon :icon-class="icon" />
</el-tooltip>
</li>
</ul>
</el-scrollbar>
</el-tab-pane>
<el-tab-pane label="Element 图标" name="element">
<el-scrollbar height="300px">
<ul class="icon-container">
<li
v-for="icon in filteredEpIcons"
:key="icon"
class="icon-item"
@click="selectIcon(icon)"
>
<el-icon>
<component :is="icon" />
</el-icon>
</li>
</ul>
</el-scrollbar>
</el-tab-pane>
</el-tabs>
</div>
</el-popover>
</div>
</template>
<script setup lang="ts">
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
const props = defineProps({
modelValue: {
type: String,
require: false,
default: "",
},
width: {
type: String,
require: false,
default: "500px",
},
});
const emit = defineEmits(["update:modelValue"]);
const selectedIcon = toRef(props, "modelValue");
const iconSelectRef = ref();
const popoverContentRef = ref();
const activeTab = ref("svg"); // 默认激活的Tab
const searchText = ref(""); // 筛选的值
const popoverVisible = ref(false); // 弹窗显示状态
const svgIcons: string[] = []; // SVG图标集合
const filteredSvgIcons = ref<string[]>([]); // 过滤后的SVG图标名称集合
const epIcons: string[] = Object.keys(ElementPlusIconsVue); // Element Plus图标集合
const filteredEpIcons = ref<string[]>([]); // 过滤后的Element Plus图标名称集合
onMounted(() => {
loadIcons();
});
/**
* icon 加载
*/
function loadIcons() {
const icons = import.meta.glob("../../assets/icons/*.svg");
for (const path in icons) {
const iconName = path.replace(/.*\/(.*)\.svg$/, "$1");
svgIcons.push(iconName);
}
filteredSvgIcons.value = svgIcons;
}
/**
* 选项卡切换
*/
function handleTabClick(tabPane: any) {
activeTab.value = tabPane.name;
filterIcons();
}
/**
* icon 筛选
*/
function filterIcons() {
if (activeTab.value === "svg") {
// 过滤SVG图标逻辑
filteredSvgIcons.value = searchText.value
? svgIcons.filter((iconName) =>
iconName.toLowerCase().includes(searchText.value.toLowerCase())
)
: svgIcons;
} else {
// 过滤Element Plus图标逻辑 TODO
filteredEpIcons.value = searchText.value
? epIcons.filter((iconName) =>
iconName.toLowerCase().includes(searchText.value.toLowerCase())
)
: epIcons;
}
}
/**
* 选择图标
*/
function selectIcon(iconName: string) {
if (activeTab.value === "element") {
iconName = "el-icon-" + iconName;
}
emit("update:modelValue", iconName);
popoverVisible.value = false;
}
/**
* 点击容器外的区域关闭弹窗 VueUse onClickOutside
*/
onClickOutside(iconSelectRef, () => (popoverVisible.value = false), {
ignore: [popoverContentRef],
});
</script>
<style scoped lang="scss">
.reference :deep(.el-input__wrapper),
.reference :deep(.el-input__inner) {
cursor: pointer;
}
.icon-container {
display: flex;
flex-wrap: wrap;
.icon-item {
display: flex;
align-items: center;
justify-content: center;
padding: 8px;
margin: 4px;
cursor: pointer;
border: 1px solid #dcdfe6;
border-radius: 4px;
transition: all 0.3s;
}
.icon-item:hover {
border-color: #4080ff;
scale: 1.2;
}
}
</style>
+52
View File
@@ -0,0 +1,52 @@
<template>
<div class="icp-info" ref="icpRef">
<div>Copyright © 2013 - 2024 iChangzuo.com All Rights Reserved.</div>
<div class="icp"><a href="http://beian.miit.gov.cn" target="_blank">苏ICP备13035645号-1</a></div>
</div>
</template>
<script setup>
const icpRef = ref();
const { width } = useWindowSize();
/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
if (width.value < 520) {
if (icpRef.value) {
icpRef.value.style = "display: inline;";
}
} else {
if (icpRef.value) {
icpRef.value.style = "display: flex;";
}
}
});
</script>
<style lang="scss" scoped>
.icp-info {
position: fixed;
width: 100%;
bottom: 4px;
font-size: 12px;
text-align: center;
display: flex;
justify-content: space-between;
div {
display: inline-block;
margin: 0 10px 0 10px;
}
a {
cursor: pointer;
text-decoration: none;
}
a:focus,
a:hover {
color: inherit;
text-decoration: underline;
}
}
</style>
+47
View File
@@ -0,0 +1,47 @@
<template>
<el-dropdown trigger="click" @command="handleLanguageChange">
<div>
<svg-icon icon-class="language" :size="size" />
</div>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
v-for="item in langOptions"
:key="item.value"
:disabled="appStore.language === item.value"
:command="item.value"
>
{{ item.label }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</template>
<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { useAppStore } from "@/store/modules/app";
import { LanguageEnum } from "@/enums/LanguageEnum";
defineProps({
size: {
type: String,
required: false,
},
});
const langOptions = [
{ label: "中文", value: LanguageEnum.ZH_CN },
{ label: "English", value: LanguageEnum.EN },
];
const appStore = useAppStore();
const { locale, t } = useI18n();
function handleLanguageChange(lang: string) {
locale.value = lang;
appStore.changeLanguage(lang);
ElMessage.success(t("langSelect.message.success"));
}
</script>
+472
View File
@@ -0,0 +1,472 @@
<template>
<el-dialog
v-model="dialogVisible"
:show-close="false"
width="400px"
close-on-click-modal
destroy-on-close
@close="handleClose"
>
<div class="login-container" v-loading="dlgLoading">
<!-- 注册表单 -->
<el-card class="login-card">
<el-tabs v-model="actTab" type="card" @tab-change="tabChanged">
<el-tab-pane class="w-[300px]" v-for="(label, key) in tabTypes" :label="label" :name="label" :key="key" />
</el-tabs>
<div class="text-center relative">
<h2>{{ tabTitle() }}</h2>
</div>
<el-form v-if="isRegTab" ref="regFormRef" :model="regData" :rules="regRules" class="login-form">
<!-- 用户名 -->
<el-form-item prop="username">
<div class="input-wrapper">
<i-ep-user class="mx-2" />
<el-input
ref="username"
v-model="regData.username"
placeholder="请输入手机或邮箱号"
name="username"
size="large"
maxlength="40"
class="h-[48px]"
/>
</div>
</el-form-item>
<!-- 密码 -->
<el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
<el-form-item prop="password">
<div class="input-wrapper">
<i-ep-lock class="mx-2" />
<el-input
v-model="regData.password"
placeholder="请输入密码"
type="password"
name="password"
@keyup="checkCapslock"
size="large"
class="h-[48px] pr-2"
show-password
/>
</div>
</el-form-item>
</el-tooltip>
<!-- 重复密码 -->
<el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
<el-form-item prop="repeatPassword">
<div class="input-wrapper">
<i-ep-lock class="mx-2" />
<el-input
v-model="regData.repeatPassword"
placeholder="请再次输入密码"
type="password"
name="repeatPassword"
@keyup="checkCapslock"
size="large"
class="h-[48px] pr-2"
show-password
/>
</div>
</el-form-item>
</el-tooltip>
<!-- 注册验证码 -->
<div class="flex flex-justify-between w-full">
<el-form-item prop="captchaCode" class="w-[200px]">
<div class="input-wrapper">
<svg-icon icon-class="captcha" class="mx-2" />
<el-input
v-model="regData.verifyCode"
auto-complete="off"
size="large"
class="flex-1"
:placeholder="$t('login.captchaCode')"
@keyup.enter="handleLoginSubmit"
/>
</div>
</el-form-item>
<SendCodeButton ref="sendButtonRef" @sendCodeClick="handleSendCode" @updateCaptcha="handleCaptchaData" />
</div>
<el-form-item style="border: none; height: 40px">
<div class="tips-wrapper">
<el-checkbox v-model="agreeChecked">
<span>同意</span>
<a href="/helper?page=user">《唱作网用户协议》</a>
</el-checkbox>
<el-button link style="color: #50b6ff" @click="beforeTo">找回密码?</el-button>
</div>
</el-form-item>
<!-- 注册按钮 -->
<el-button type="primary" size="large" class="w-full" @click.prevent="handleRegisterSubmit">
{{ $t("login.register") }}
</el-button>
</el-form>
<!-- 登录表单 -->
<el-form v-else ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
<!-- 用户名 -->
<el-form-item prop="username">
<div class="input-wrapper">
<i-ep-user class="mx-2" />
<el-input
ref="username"
v-model="loginData.username"
:placeholder="$t('login.username')"
name="username"
size="large"
maxlength="40"
class="h-[48px]"
/>
</div>
</el-form-item>
<!-- 密码 -->
<el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
<el-form-item prop="password">
<div class="input-wrapper">
<i-ep-lock class="mx-2" />
<el-input
v-model="loginData.password"
:placeholder="$t('login.password')"
type="password"
name="password"
@keyup="checkCapslock"
@keyup.enter="handleLoginSubmit"
size="large"
class="h-[48px] pr-2"
show-password
/>
</div>
</el-form-item>
</el-tooltip>
<!-- 验证码 -->
<el-form-item prop="captchaCode">
<div class="input-wrapper">
<svg-icon icon-class="captcha" class="mx-2" />
<el-input
v-model="loginData.captchaCode"
auto-complete="off"
size="large"
class="flex-1"
:placeholder="$t('login.captchaCode')"
@keyup.enter="handleLoginSubmit"
/>
<el-image @click="getCaptcha" :src="captchaBase64" class="captcha-image" />
</div>
</el-form-item>
<el-form-item style="border: none; height: 40px">
<div class="tips-wrapper">
<el-checkbox v-model="remChecked">
<span style="color: #409eff">记住密码</span>
<!-- <label style="color: #949493">(不是自己电脑请勿勾选)</label> -->
</el-checkbox>
<el-button link style="color: #50b6ff" @click="beforeTo">找回密码?</el-button>
</div>
</el-form-item>
<!-- 登录按钮 -->
<el-button type="primary" size="large" class="w-full" @click.prevent="handleLoginSubmit">
{{ $t("login.login") }}
</el-button>
</el-form>
</el-card>
</div>
</el-dialog>
</template>
<script setup lang="ts" name="LoginDialog">
// 外部库和依赖
import { useRoute } from "vue-router";
import { TabPaneName } from "element-plus";
// 内部依赖
import { useUserStore, useAppStore } from "@/store";
import AuthAPI, { CaptchaData, RegisterData, SendCodeData, type LoginData } from "@/api/auth";
import router from "@/router";
// 类型定义
import type { FormInstance, FormRules } from "element-plus";
// 导入 login.scss 文件
import "@/styles/login.scss";
import { isEmail, isPhone } from "@/utils";
const props = defineProps({
visible: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["update:visible", "close"]);
const dialogVisible = computed({
get: () => props.visible,
set: (val) => {
emit("update:visible", val);
},
});
const actTab = ref("登录");
const tabTypes = ["登录", "注册"];
const isRegTab = ref(false);
const sendButtonRef = ref();
const handleClose = () => {
dialogVisible.value = false;
};
// 使用导入的依赖和库
const userStore = useUserStore();
const route = useRoute();
// 国际化 Internationalization
const { t } = useI18n();
// 按钮 loading 状态
const dlgLoading = ref(false);
// 是否大写锁定
const isCapslock = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 登录表单ref
const loginFormRef = ref<FormInstance>();
// 注册表单ref
const regFormRef = ref<FormInstance>();
const remChecked = ref(true);
const agreeChecked = ref(true);
function tabChanged(name: TabPaneName) {
actTab.value = name as string;
isRegTab.value = name != "登录";
loginFormRef.value?.clearValidate();
regFormRef.value?.clearValidate();
}
function tabTitle() {
return isRegTab.value ? "注册新用户" : "登录唱作网";
}
const regData = ref<RegisterData>({
username: "",
password: "",
repeatPassword: "",
verifyCode: "",
});
const regRules = reactive<FormRules<typeof regData>>({
username: [{ required: true, message: "请输入手机或邮箱号", trigger: "blur", validator: validateRegName }],
password: [{ required: true, message: "请输入长度为6-16的密码", trigger: "blur", validator: validatePassword }],
repeatPassword: [
{ required: true, message: "请再次输入相同密码", trigger: "blur", validator: validateRepeatPassword },
],
verifyCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
function validateRegName(rule: any, value: string, callback: any) {
if (!isPhone(regData.value.username) && !isEmail(regData.value.username)) {
callback(new Error("请输入手机或邮箱号"));
} else {
callback();
}
}
function validatePassword(rule: any, value: string, callback: any) {
if (value.length < 6 || value.length > 16) {
callback(new Error("请输入长度为6-16的密码"));
} else {
callback();
}
}
function validateRepeatPassword(rule: any, value: string, callback: any) {
if (value !== regData.value.password) {
callback(new Error("请再次输入相同密码"));
} else {
callback();
}
}
const loginData = ref<LoginData>({
username: "",
password: "",
captchaKey: "",
captchaCode: "",
});
const loginRules = reactive<FormRules<typeof loginData>>({
username: [
{
required: true,
trigger: "blur",
message: t("login.message.username.required"),
},
],
password: [
{
required: true,
trigger: "blur",
message: t("login.message.password.required"),
},
{
min: 3,
message: t("login.message.password.min"),
trigger: "blur",
},
],
captchaCode: [
{
required: true,
trigger: "blur",
message: t("login.message.captchaCode.required"),
},
],
});
/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
// 防止浏览器密码自动填充时报错
if (event instanceof KeyboardEvent) {
isCapslock.value = event.getModifierState("CapsLock");
}
}
/** 获取验证码 */
function getCaptcha() {
AuthAPI.getCaptcha().then((data) => {
loginData.value.captchaKey = data.captchaKey;
captchaBase64.value = data.captchaBase64;
});
}
/** 获得防刷验证码后,正式请求注册验证码 */
function handleCaptchaData(data: CaptchaData) {
dlgLoading.value = true;
const sendData: SendCodeData = {
contact: regData.value.username,
captchaKey: data.captchaKey,
captchaCode: data.captchaCode,
};
AuthAPI.sendCode(sendData)
.then((data) => {
sendButtonRef.value.startCountdown(); //开始倒计时
ElMessage.success("已向 " + regData.value.username + " 发送验证码(15分钟内有效,请勿重复提交!)");
})
.finally(() => {
dlgLoading.value = false;
});
}
/** 先检验手机或邮箱,再进行防刷 */
function handleSendCode() {
regFormRef.value?.validateField(["username"], (valid: boolean) => {
if (valid) {
sendButtonRef.value.handleClick();
}
});
}
/** 登录表单提交 */
function handleLoginSubmit() {
loginFormRef.value?.validate((valid: boolean) => {
if (valid) {
dlgLoading.value = true;
userStore
.login(loginData.value)
.then(() => {
if (remChecked.value) {
const logData = { username: loginData.value.username, password: loginData.value.password };
localStorage.setItem("loginSet", JSON.stringify(logData));
} else {
localStorage.setItem("loginSet", JSON.stringify({}));
}
dialogVisible.value = false;
nextTick(() => {
router.push("/dashboard");
});
})
//
.catch((err) => {
getCaptcha();
})
.finally(() => {
dlgLoading.value = false;
});
}
});
}
/** 注册表单提交 */
function handleRegisterSubmit() {
if (!agreeChecked.value) {
ElMessage.warning("请勾选'同意'再进行注册");
return;
}
regFormRef.value?.validate((valid: boolean) => {
if (valid) {
dlgLoading.value = true;
userStore
.register(regData.value)
.then(() => {
localStorage.setItem("loginSet", JSON.stringify({}));
dialogVisible.value = false;
useAppStore().stopSendCodeCountdown(); //注册成功,中止验证码倒计时
nextTick(() => {
router.push("/dashboard");
});
})
.finally(() => {
dlgLoading.value = false;
});
}
});
}
function beforeTo() {
if (route.path != "/resetPassword") {
router.push({
path: "/resetPassword",
query: {
username: loginData.value.username,
},
});
} else {
handleClose();
}
}
onBeforeUpdate(() => {
if (dialogVisible.value) {
getCaptcha();
}
});
onMounted(() => {
const loginSet = localStorage.getItem("loginSet");
if (loginSet != null) {
const data = JSON.parse(loginSet);
if (Object.keys(data).length == 2) {
loginData.value.username = data.username;
loginData.value.password = data.password;
} else {
remChecked.value = false;
}
}
});
</script>
<style lang="scss" scoped></style>
+143
View File
@@ -0,0 +1,143 @@
<template>
<div class="nav-action-item" @click="showSearchModal">
<svg-icon icon-class="search" />
<el-dialog v-model="visible" width="30%" :append-to-body="true" :show-close="false" @close="hideSearchModal">
<template #header>
<el-input
ref="menuSearchInput"
v-model="searchKey"
size="large"
placeholder="搜索"
clearable
@keyup.enter="inputSearch"
@input="inputSearch"
>
<template #prepend>
<el-button icon="Search" />
</template>
</el-input>
</template>
<div class="search-content">
<ul v-if="searchResult.length > 0">
<li v-for="(item, index) in searchResult" :key="index" @click="toMenu(item)">
<el-icon v-if="item.icon && item.icon.startsWith('el-icon')" class="sub-el-icon">
<component :is="item.icon.replace('el-icon-', '')" />
</el-icon>
<svg-icon v-else-if="item.icon" :icon-class="item.icon" />
<svg-icon v-else icon-class="menu" />
{{ item.title }}
</li>
</ul>
<div class="search-space" v-else>暂无数据</div>
</div>
<template #footer></template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import router from "@/router";
const visible = ref(false);
const searchKey = ref("");
import { usePermissionStore } from "@/store";
import { isExternal } from "@/utils";
import { RouteRecordRaw } from "vue-router";
const permissionStore = usePermissionStore();
//获取当前拥有的路由
const menuSearchInput = ref();
const noSearchRoutePath = ref(["/redirect", "/login", "/401", "/404"]);
const searchData = ref<SearchItem[]>([]);
const searchResult = ref<SearchItem[]>([]);
function showSearchModal() {
searchKey.value = "";
searchResult.value = [];
visible.value = true;
setTimeout(() => {
menuSearchInput.value.focus();
}, 100);
}
function hideSearchModal() {
visible.value = false;
}
function inputSearch() {
searchResult.value = [];
if (searchKey.value) {
let toLowerCaseKey = searchKey.value.toLowerCase();
searchResult.value = searchData.value.filter((item) => item.toLowerCaseTitle.includes(toLowerCaseKey));
}
}
onMounted(() => {
searchResult.value = [];
initSearchData(permissionStore.routes);
});
function initSearchData(routes: RouteRecordRaw[], parentPath: string = "") {
parentPath = parentPath === "/" ? "" : parentPath;
routes.forEach((item: any) => {
if (noSearchRoutePath.value.includes(item.path)) {
return;
}
let path = item.path.startsWith("/") ? item.path : parentPath + "/" + item.path;
path = isExternal(item.path) ? item.path : path;
if (item.children) {
initSearchData(item.children, path);
} else if (item.meta && item.meta.title && item.path) {
let title = item.meta.title == "dashboard" ? "首页" : item.meta.title;
let toLowerCaseTitle = title.toLowerCase();
searchData.value.push({
title: title,
toLowerCaseTitle: toLowerCaseTitle,
path: path,
name: item.name,
icon: item.meta.icon,
redirect: item.redirect ? item.redirect : undefined,
});
}
});
}
function toMenu(item: SearchItem) {
hideSearchModal();
if (isExternal(item.path)) {
window.open(item.path, "_blank");
} else {
router.push(item.path);
}
}
interface SearchItem {
title: string;
toLowerCaseTitle: string;
path: string;
name: string;
icon?: string;
redirect?: string;
}
</script>
<style scoped>
.search-content ul li {
padding-left: 10px;
line-height: 40px;
text-align: left;
&:hover {
background-color: #f5f5f5;
}
}
.search-content {
max-height: 400px;
overflow-y: auto;
}
.search-space {
padding: 20px;
color: #999;
text-align: center;
}
</style>
+94
View File
@@ -0,0 +1,94 @@
<template>
<!-- 消息通知 -->
<el-dropdown class="message nav-action-item" trigger="click" @visible-change="dropChange">
<el-badge :is-dot="showDot">
<div class="flex-center h100% p10px">
<i-ep-bell />
</div>
</el-badge>
<template #dropdown>
<div class="px-5 py-2">
<el-tabs v-model="actTab" @tab-change="tabChanged">
<el-tab-pane
class="w-[300px]"
v-for="(label, key) in MessageTypeLabels"
:label="label"
:name="label"
:key="key"
>
<div class="p-2" v-for="msg in getFilteredMessages(key)" :key="msg.msgId">
<el-link type="primary" @click="showMsg(msg.msgId!)">
<el-text class="w-280px" truncated>
{{ msg.title }}
</el-text>
</el-link>
</div>
</el-tab-pane>
</el-tabs>
<el-divider />
<div class="flex-x-between">
<el-link type="primary" :underline="false" @click="showMore">
<span class="text-xs">查看更多</span>
<el-icon class="text-xs"><ArrowRight /></el-icon>
</el-link>
</div>
</div>
</template>
</el-dropdown>
</template>
<script setup lang="ts" name="MsgTip">
import { useUserStore } from "@/store";
import { MessageTypeLabels } from "@/enums/MessageTypeEnum";
import router from "@/router";
import { TabPaneName } from "element-plus";
const userStore = useUserStore();
const messages = ref(userStore.msgLatest);
const actTab = ref(MessageTypeLabels[0]);
const showDot = computed(() => {
return messages.value.some((item) => {
return item.type == 0 || item.state == 0;
});
});
const getFilteredMessages = (type: number) => {
const result = messages.value.filter((m) => m.type == type);
return result;
};
function tabChanged(name: TabPaneName) {
actTab.value = name as string;
}
function dropChange(val: boolean) {
if (val && messages.value.some((m) => m.type == 1)) {
actTab.value = MessageTypeLabels[1];
}
}
function showMsg(id: number) {
const msg = messages.value.find((m) => m.msgId == id);
if (msg) {
ElMessageBox({
title: msg.title,
message: msg.content,
dangerouslyUseHTMLString: true,
confirmButtonText: "OK",
callback: () => {
if (actTab.value == MessageTypeLabels[1]) {
userStore.setMessageState([msg.msgId!], 1, true);
}
},
});
}
}
function showMore() {
router.push({ name: "Messages" });
}
</script>
+81
View File
@@ -0,0 +1,81 @@
<template>
<el-scrollbar>
<div :class="{ hidden: hidden }" class="pagination">
<el-pagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:background="background"
:layout="layout"
:page-sizes="pageSizes"
:total="total"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</div>
</el-scrollbar>
</template>
<script setup lang="ts">
const props = defineProps({
total: {
required: true,
type: Number as PropType<number>,
default: 0,
},
page: {
type: Number,
default: 1,
},
limit: {
type: Number,
default: 20,
},
pageSizes: {
type: Array as PropType<number[]>,
default() {
return [10, 20, 30, 50];
},
},
layout: {
type: String,
default: "total, sizes, prev, pager, next, jumper",
},
background: {
type: Boolean,
default: true,
},
autoScroll: {
type: Boolean,
default: true,
},
hidden: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["pagination", "update:page", "update:limit"]);
const currentPage = useVModel(props, "page", emit);
const pageSize = useVModel(props, "limit", emit);
function handleSizeChange(val: number) {
emit("pagination", { page: currentPage, limit: val });
}
function handleCurrentChange(val: number) {
currentPage.value = val;
emit("pagination", { page: val, limit: props.limit });
}
</script>
<style lang="scss" scoped>
.pagination {
padding: 12px;
&.hidden {
display: none;
}
}
</style>
+147
View File
@@ -0,0 +1,147 @@
<template>
<el-button
type="success"
size="large"
style="width: 110px"
:disabled="sendCodeDisable"
@click="emitEvents('sendCodeClick')"
>
{{ sendCodeText }}
</el-button>
<div class="captcha-dialog">
<el-dialog
v-model="dialogVisible"
width="350px"
top="30vh"
title="人机验证"
destroy-on-close
:close-on-click-modal="false"
>
<el-form :model="captchaData" :rules="captchaRules" ref="capthaFormRef" @submit.native.prevent>
<el-form-item prop="captchaCode">
<div class="input-wrapper">
<svg-icon icon-class="captcha" class="mx-2" />
<el-input
v-model="captchaData.captchaCode"
size="large"
class="flex-1"
placeholder="人机验证码"
@keyup.enter="handleCaptchConfirm"
/>
<el-image @click="getCaptcha" :src="captchaBase64" class="captcha-image" />
</div>
</el-form-item>
<el-button type="primary" size="large" class="w-full" @click.prevent="handleCaptchConfirm">确定</el-button>
</el-form>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { useAppStoreHook } from "@/store/modules/app";
import AuthAPI, { CaptchaData } from "@/api/auth";
import { FormInstance } from "element-plus";
defineOptions({
name: "SendCodeButton",
inheritAttrs: true,
});
const emitEvents = defineEmits(["sendCodeClick", "updateCaptcha"]);
defineExpose({ handleClick, startCountdown });
const appStore = useAppStoreHook();
const sendCodeDisable = computed(() => {
return appStore.sendCodeDuration > 0;
});
const sendCodeText = computed(() => {
return appStore.sendCodeDuration <= 0 ? "获取验证码" : `${appStore.sendCodeDuration}秒`;
});
const captchaBase64 = ref();
const capthaFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const captchaData = ref<CaptchaData>({
captchaKey: "",
captchaCode: "",
});
const captchaRules = reactive({
captchaCode: [{ required: true, trigger: "blur", message: "请输入防刷验证码" }],
});
/** 获取验证码 */
function getCaptcha() {
AuthAPI.getCaptcha().then((data) => {
captchaData.value.captchaKey = data.captchaKey;
captchaData.value.captchaCode = "";
captchaBase64.value = data.captchaBase64;
});
}
function handleCaptchConfirm() {
capthaFormRef.value?.validateField(["captchaCode"], (valid: boolean) => {
if (valid) {
dialogVisible.value = false;
emitEvents("updateCaptcha", captchaData.value);
}
});
}
function startCountdown() {
appStore.startSendCodeCountdown();
}
function handleClick() {
getCaptcha();
// capthaFormRef.value?.resetFields();
capthaFormRef.value?.clearValidate();
dialogVisible.value = true;
}
</script>
<style lang="scss" scoped>
.captcha-dialog {
.input-wrapper {
display: flex;
align-items: center;
width: 100%;
}
.captcha-image {
height: 48px;
cursor: pointer;
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
}
:deep(.el-form-item) {
background: var(--el-input-bg-color);
border: 1px solid var(--el-border-color);
border-radius: 5px;
margin-bottom: 22px !important;
}
:deep(.el-input) {
.el-input__wrapper {
padding: 0;
background-color: transparent;
box-shadow: none;
&.is-focus,
&:hover {
box-shadow: none !important;
}
input:-webkit-autofill {
/* 通过延时渲染背景色变相去除背景颜色 */
transition: background-color 1000s ease-in-out 0s;
}
}
}
:deep(.el-overlay) {
background-color: rgba(0, 0, 0, 1);
}
</style>
+39
View File
@@ -0,0 +1,39 @@
<template>
<el-dropdown trigger="click" @command="handleSizeChange">
<div>
<svg-icon icon-class="size" />
</div>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
v-for="item of sizeOptions"
:key="item.value"
:disabled="appStore.size == item.value"
:command="item.value"
>
{{ item.label }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</template>
<script setup lang="ts">
import { SizeEnum } from "@/enums/SizeEnum";
import { useAppStore } from "@/store/modules/app";
const { t } = useI18n();
const sizeOptions = computed(() => {
return [
{ label: t("sizeSelect.default"), value: SizeEnum.DEFAULT },
{ label: t("sizeSelect.large"), value: SizeEnum.LARGE },
{ label: t("sizeSelect.small"), value: SizeEnum.SMALL },
];
});
const appStore = useAppStore();
function handleSizeChange(size: string) {
appStore.changeSize(size);
ElMessage.success(t("sizeSelect.message.success"));
}
</script>
+41
View File
@@ -0,0 +1,41 @@
<template>
<svg aria-hidden="true" class="svg-icon" :style="'width:' + size + ';height:' + size">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
const props = defineProps({
prefix: {
type: String,
default: "icon",
},
iconClass: {
type: String,
required: false,
default: "",
},
color: {
type: String,
default: "",
},
size: {
type: String,
default: "1em",
},
});
const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>
<style scoped>
.svg-icon {
display: inline-block;
width: 1em;
height: 1em;
overflow: hidden;
vertical-align: -0.15em; /* 因icon大小被设置为和字体大小一致,而span等标签的下边缘会和字体的基线对齐,故需设置一个往下的偏移比例,来纠正视觉上的未对齐效果 */
outline: none;
fill: currentcolor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
}
</style>
+371
View File
@@ -0,0 +1,371 @@
<template>
<div ref="tableSelectRef" :style="'width:' + width">
<el-popover
:visible="popoverVisible"
:width="popoverWidth"
placement="bottom-end"
v-bind="selectConfig.popover"
@show="handleShow"
>
<template #reference>
<div @click="popoverVisible = !popoverVisible">
<slot>
<el-input
class="reference"
:model-value="text"
:readonly="true"
:placeholder="placeholder"
>
<template #suffix>
<el-icon
:style="{
transform: popoverVisible ? 'rotate(180deg)' : 'rotate(0)',
transition: 'transform .5s',
}"
>
<ArrowDown />
</el-icon>
</template>
</el-input>
</slot>
</div>
</template>
<!-- 弹出框内容 -->
<div ref="popoverContentRef">
<!-- 表单 -->
<el-form ref="formRef" :model="queryParams" :inline="true">
<template v-for="item in selectConfig.formItems" :key="item.prop">
<el-form-item :label="item.label" :prop="item.prop">
<!-- Input 输入框 -->
<template v-if="item.type === 'input'">
<template v-if="item.attrs?.type === 'number'">
<el-input
v-model.number="queryParams[item.prop]"
v-bind="item.attrs"
@keyup.enter="handleQuery"
/>
</template>
<template v-else>
<el-input
v-model="queryParams[item.prop]"
v-bind="item.attrs"
@keyup.enter="handleQuery"
/>
</template>
</template>
<!-- Select 选择器 -->
<template v-else-if="item.type === 'select'">
<el-select v-model="queryParams[item.prop]" v-bind="item.attrs">
<template v-for="option in item.options" :key="option.value">
<el-option :label="option.label" :value="option.value" />
</template>
</el-select>
</template>
<!-- TreeSelect 树形选择 -->
<template v-else-if="item.type === 'tree-select'">
<el-tree-select
v-model="queryParams[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- DatePicker 日期选择器 -->
<template v-else-if="item.type === 'date-picker'">
<el-date-picker
v-model="queryParams[item.prop]"
v-bind="item.attrs"
/>
</template>
<!-- Input 输入框 -->
<template v-else>
<template v-if="item.attrs?.type === 'number'">
<el-input
v-model.number="queryParams[item.prop]"
v-bind="item.attrs"
@keyup.enter="handleQuery"
/>
</template>
<template v-else>
<el-input
v-model="queryParams[item.prop]"
v-bind="item.attrs"
@keyup.enter="handleQuery"
/>
</template>
</template>
</el-form-item>
</template>
<el-form-item>
<el-button type="primary" icon="search" @click="handleQuery">
搜索
</el-button>
<el-button icon="refresh" @click="handleReset">重置</el-button>
</el-form-item>
</el-form>
<!-- 列表 -->
<el-table
ref="tableRef"
v-loading="loading"
:data="pageData"
:border="true"
:max-height="250"
:row-key="pk"
:highlight-current-row="true"
:class="{ radio: !isMultiple }"
@select="handleSelect"
@select-all="handleSelectAll"
>
<template v-for="col in selectConfig.tableColumns" :key="col.prop">
<!-- 自定义 -->
<template v-if="col.templet === 'custom'">
<el-table-column v-bind="col">
<template #default="scope">
<slot
:name="col.slotName ?? col.prop"
:prop="col.prop"
v-bind="scope"
></slot>
</template>
</el-table-column>
</template>
<!-- 其他 -->
<template v-else>
<el-table-column v-bind="col" />
</template>
</template>
</el-table>
<!-- 分页 -->
<pagination
v-if="total > 0"
v-model:total="total"
v-model:page="queryParams.pageNum"
v-model:limit="queryParams.pageSize"
@pagination="handlePagination"
/>
<div class="feedback">
<el-button type="primary" size="small" @click="handleConfirm">
{{ confirmText }}
</el-button>
<el-button size="small" @click="handleClear"> 清 空 </el-button>
<el-button size="small" @click="handleClose"> 关 闭 </el-button>
</div>
</div>
</el-popover>
</div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { onClickOutside, useResizeObserver } from "@vueuse/core";
import type { FormInstance, PopoverProps, TableInstance } from "element-plus";
// 对象类型
export type IObject = Record<string, any>;
// 定义接收的属性
export interface ISelectConfig<T = any> {
// 宽度
width?: string;
// 占位符
placeholder?: string;
// popover组件属性
popover?: Partial<Omit<PopoverProps, "visible" | "v-model:visible">>;
// 列表的网络请求函数(需返回promise)
indexAction: (queryParams: T) => Promise<any>;
// 主键名(跨页选择必填,默认为id)
pk?: string;
// 多选
multiple?: boolean;
// 表单项
formItems: Array<{
// 组件类型(如input,select等)
type?: "input" | "select" | "tree-select" | "date-picker";
// 标签文本
label: string;
// 键名
prop: string;
// 组件属性
attrs?: IObject;
// 初始值
initialValue?: any;
// 可选项(适用于select组件)
options?: { label: string; value: any }[];
}>;
// 列选项
tableColumns: Array<{
type?: "default" | "selection" | "index" | "expand";
label?: string;
prop?: string;
width?: string | number;
[key: string]: any;
}>;
}
const props = withDefaults(
defineProps<{
selectConfig: ISelectConfig;
text?: string;
}>(),
{
text: "",
}
);
// 自定义事件
const emit = defineEmits<{
confirmClick: [selection: any[]];
}>();
// 主键
const pk = props.selectConfig.pk ?? "id";
// 是否多选
const isMultiple = props.selectConfig.multiple === true;
// 宽度
const width = props.selectConfig.width ?? "100%";
// 占位符
const placeholder = props.selectConfig.placeholder ?? "请选择";
// 是否显示弹出框
const popoverVisible = ref(false);
// 加载状态
const loading = ref(false);
// 数据总数
const total = ref(0);
// 列表数据
const pageData = ref<IObject[]>([]);
// 每页条数
const pageSize = 10;
// 搜索参数
const queryParams = reactive<{
pageNum: number;
pageSize: number;
[key: string]: any;
}>({
pageNum: 1,
pageSize: pageSize,
});
// 计算popover的宽度
const tableSelectRef = ref();
const popoverWidth = ref(width);
useResizeObserver(tableSelectRef, (entries) => {
popoverWidth.value = `${entries[0].contentRect.width}px`;
});
// 表单操作
const formRef = ref<FormInstance>();
// 初始化搜索条件
for (const item of props.selectConfig.formItems) {
queryParams[item.prop] = item.initialValue ?? "";
}
// 重置操作
function handleReset() {
formRef.value?.resetFields();
fetchPageData(true);
}
// 查询操作
function handleQuery() {
fetchPageData(true);
}
// 获取分页数据
function fetchPageData(isRestart = false) {
loading.value = true;
if (isRestart) {
queryParams.pageNum = 1;
queryParams.pageSize = pageSize;
}
props.selectConfig
.indexAction(queryParams)
.then((data) => {
total.value = data.total;
pageData.value = data.list;
})
.finally(() => {
loading.value = false;
});
}
// 列表操作
const tableRef = ref<TableInstance>();
// 数据刷新后是否保留选项
for (const item of props.selectConfig.tableColumns) {
if (item.type === "selection") {
item.reserveSelection = true;
break;
}
}
// 选择
const selectedItems = ref<IObject[]>([]);
const confirmText = computed(() => {
return selectedItems.value.length > 0
? `已选(${selectedItems.value.length})`
: "确 定";
});
function handleSelect(selection: any[], row: any) {
if (isMultiple || selection.length === 0) {
// 多选
selectedItems.value = selection;
} else {
// 单选
selectedItems.value = [selection[selection.length - 1]];
tableRef.value?.clearSelection();
tableRef.value?.toggleRowSelection(selectedItems.value[0], true);
tableRef.value?.setCurrentRow(selectedItems.value[0]);
}
}
function handleSelectAll(selection: any[]) {
if (isMultiple) {
selectedItems.value = selection;
}
}
// 分页
function handlePagination() {
fetchPageData();
}
// 弹出框
const isInit = ref(false);
// 显示
function handleShow() {
if (isInit.value === false) {
isInit.value = true;
fetchPageData();
}
}
// 确定
function handleConfirm() {
if (selectedItems.value.length === 0) {
ElMessage.error("请选择数据");
return;
}
popoverVisible.value = false;
emit("confirmClick", selectedItems.value);
}
// 清空
function handleClear() {
tableRef.value?.clearSelection();
selectedItems.value = [];
}
// 关闭
function handleClose() {
popoverVisible.value = false;
}
const popoverContentRef = ref();
/* onClickOutside(tableSelectRef, () => (popoverVisible.value = false), {
ignore: [popoverContentRef],
}); */
</script>
<style scoped lang="scss">
.reference :deep(.el-input__wrapper),
.reference :deep(.el-input__inner) {
cursor: pointer;
}
.feedback {
display: flex;
justify-content: flex-end;
margin-top: 6px;
}
// 隐藏全选按钮
.radio :deep(.el-table__header th.el-table__cell:nth-child(1) .el-checkbox) {
visibility: hidden;
}
</style>
+190
View File
@@ -0,0 +1,190 @@
<template>
<div class="top-bar">
<!--左侧链接-->
<div class="bar-left">
<div class="top-logo"><img :src="logo" /></div>
<div class="top-link">
<router-link to="/software"><span>软件下载</span></router-link>
</div>
<div class="top-link">
<router-link to="/helper"><span>帮助中心</span></router-link>
</div>
</div>
<!-- 导航栏右侧 -->
<div class="bar-right">
<!-- 消息提示 -->
<MsgTip v-if="isLogon && !isMobile" />
<!-- 用户头像 -->
<el-dropdown v-if="isLogon" class="nav-action-item" trigger="click">
<div class="flex-center h100% p10px">
<img :src="userAvatar" class="rounded-full mr-10px w24px w24px" />
<span>{{ userName }}</span>
</div>
<template #dropdown>
<el-dropdown-menu>
<router-link to="/dashboard">
<el-dropdown-item>{{ $t("navbar.account") }}</el-dropdown-item>
</router-link>
<router-link
to="/website"
v-if="userStore.user.roles.includes('ADMIN') || userStore.user.roles.includes('WEBMAN')"
>
<el-dropdown-item>{{ $t("navbar.website") }}</el-dropdown-item>
</router-link>
<el-dropdown-item divided @click="logout">
{{ $t("navbar.logout") }}
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
<div class="nav-login" v-else>
<el-button round size="large" @click.prevent="showLogin">登录 | 注册</el-button>
</div>
<el-switch v-model="isDark" inline-prompt active-icon="Moon" inactive-icon="Sunny" @change="toggleTheme" />
</div>
</div>
</template>
<script setup lang="ts">
import { useSettingsStore, useTagsViewStore, useUserStore, useAppStore } from "@/store";
import { ThemeEnum } from "@/enums/ThemeEnum";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import { DeviceEnum } from "@/enums/DeviceEnum";
import { BASE_AVATAR_URL } from "@/utils/baseurls";
const appStore = useAppStore();
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const tagsViewStore = useTagsViewStore();
const router = useRouter();
const emit = defineEmits(["clickLogin"]);
const showLogin = () => {
emit("clickLogin");
};
const logo = ref(new URL(`@/assets/logo.png`, import.meta.url).href);
const defaultAvatar = new URL(`@/assets/images/default.jpg`, import.meta.url).href;
const userAvatar = computed(() => {
if (userStore.user.avatar == undefined) return "";
else return userStore.user.avatar == "default.jpg" ? defaultAvatar : BASE_AVATAR_URL + userStore.user.avatar;
});
const userName = computed(() => {
if (userStore.user.nickname) return userStore.user.nickname;
else return userStore.user.username;
});
const isMobile = computed(() => appStore.device === DeviceEnum.MOBILE);
const isLogon = ref(false);
// 是否暗黑模式
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
/** 主题切换 */
const toggleTheme = () => {
const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
settingsStore.changeTheme(newTheme);
};
/* 注销 */
function logout() {
ElMessageBox.confirm("确定要退出当前用户吗?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
lockScroll: false,
}).then(() => {
userStore.logout().then(() => {
tagsViewStore.delAllViews();
isLogon.value = false;
});
});
}
onMounted(() => {
isLogon.value = localStorage.getItem(TOKEN_KEY) ? true : false;
});
</script>
<style lang="scss" scoped>
.top-bar {
position: fixed;
z-index: 100;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
min-height: 2vw;
padding: 0 1em 0 1em;
background-color: white;
.bar-left {
.top-logo {
float: left;
margin: 5px 30px 0 5px;
}
.top-link {
float: left;
vertical-align: middle;
margin: 0 10px 0 10px;
padding-top: 0.7em;
a {
font-weight: 300;
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size: 1.1em;
cursor: pointer;
text-decoration: none;
&:focus,
&:hover {
color: inherit;
text-decoration: underline;
cursor: pointer;
}
}
}
}
.bar-right {
display: flex;
align-items: center;
.nav-login {
margin-right: 30px;
width: 100px;
text-align: center;
.el-button span {
font-weight: 300;
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size: 18px;
}
}
.nav-action-item {
display: inline-block;
min-width: 40px;
height: $navbar-height;
line-height: $navbar-height;
color: var(--el-text-color);
text-align: center;
cursor: pointer;
&:hover {
background: rgb(0 0 0 / 10%);
}
}
}
}
html.dark {
.top-bar {
background-color: black;
}
}
</style>
+331
View File
@@ -0,0 +1,331 @@
<!-- 文件上传组件 -->
<template>
<div>
<el-upload
v-model:file-list="fileList"
:class="props.showUploadBtn ? 'show-upload-btn' : 'hide-upload-btn'"
:style="props.style"
multiple
:headers="props.headers"
:data="props.data"
:name="props.name"
:before-upload="handleBeforeUpload"
:on-remove="handleRemove"
:on-progress="handleProgress"
:on-success="handleSuccessFile"
:on-error="handleError"
:action="props.action"
:accept="props.accept"
:limit="props.limit"
>
<el-button
type="primary"
v-if="props.showUploadBtn"
:disabled="fileList.length >= props.limit"
>
{{ props.uploadBtnText }}
</el-button>
<template #tip v-if="props.showTip">
<div class="el-upload__tip">
{{ props.tip }}
</div>
</template>
<template #file="{ file }">
<div class="el-upload-list__item-info">
<a class="el-upload-list__item-name" @click="downloadFile(file)">
<el-icon><Document /></el-icon>
<span class="el-upload-list__item-file-name">{{ file.name }}</span>
<span
class="el-icon--close"
v-if="props.showDelBtn"
@click.stop="handleRemove(file)"
>
<el-icon><Close /></el-icon>
</span>
</a>
</div>
</template>
</el-upload>
<el-progress
:style="{
display: showUploadPercent ? 'inline-flex' : 'none',
width: '100%',
}"
:percentage="uploadPercent"
:color="customColorMethod"
v-if="showUploadPercent"
/>
</div>
</template>
<script lang="ts" setup>
import {
UploadRawFile,
UploadUserFile,
UploadFile,
UploadProgressEvent,
UploadFiles,
} from "element-plus";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import FileAPI from "@/api/file";
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { ResultEnum } from "@/enums/ResultEnum";
const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
/**
* 文件集合
*/
modelValue: {
type: Array<UploadUserFile>,
default: () => [],
},
/**
* 上传地址
*/
action: {
type: String,
default: FileAPI.uploadUrl,
},
/**
* 文件上传数量限制
*/
limit: {
type: Number,
default: 10,
},
/**
* 是否显示删除按钮
*/
showDelBtn: {
type: Boolean,
default: true,
},
/**
* 是否显示上传按钮
*/
showUploadBtn: {
type: Boolean,
default: true,
},
/**
* 单个文件上传大小限制(单位byte)
*/
uploadMaxSize: {
type: Number,
default: 2 * 1024 * 1024,
},
/**
* 上传文件类型
*/
accept: {
type: String,
default: "*",
},
/**
* 上传按钮文本
*/
uploadBtnText: {
type: String,
default: "上传文件",
},
/**
* 是否展示提示信息
*/
showTip: {
type: Boolean,
default: false,
},
/**
* 提示信息内容
*/
tip: {
type: String,
default: "",
},
/**
* 请求头
*/
headers: {
type: Object,
default: () => {
return {
Authorization: localStorage.getItem(TOKEN_KEY),
};
},
},
/**
* 请求携带的额外参数
*/
data: {
type: Object,
default: () => {
return {};
},
},
/**
* 上传文件的参数名
*/
name: {
type: String,
default: "file",
},
/**
* 样式
*/
style: {
type: Object,
default: () => {
return {
width: "300px",
};
},
},
});
const fileList = ref([] as UploadUserFile[]);
const valFileList = ref([] as UploadUserFile[]);
const showUploadPercent = ref(false);
const uploadPercent = ref(0);
watch(
() => props.modelValue,
(newVal: UploadUserFile[]) => {
const filePaths = fileList.value.map((file) => file.url);
const fileNames = fileList.value.map((file) => file.name);
// 监听modelValue文件集合值未变化时,跳过赋值
if (
filePaths.length > 0 &&
filePaths.length === newVal.length &&
filePaths.every((x) => newVal.some((y) => y.url === x)) &&
newVal.every((y) => filePaths.some((x) => x === y.url)) &&
fileNames.every((x) => newVal.some((y) => y.name === x)) &&
newVal.every((y) => fileNames.some((x) => x === y.name))
) {
return;
}
if (newVal.length <= 0) {
fileList.value = [];
return;
}
fileList.value = newVal.map((file) => {
return { name: file.name, url: file.url } as UploadFile;
});
valFileList.value = newVal.map((file) => {
return { name: file.name, url: file.url } as UploadFile;
});
},
{ immediate: true }
);
/**
* 限制用户上传文件的大小
*/
function handleBeforeUpload(file: UploadRawFile) {
if (file.size > props.uploadMaxSize) {
ElMessage.warning(
"上传文件不能大于" + Math.trunc(props.uploadMaxSize / 1024 / 1024) + "M"
);
return false;
}
uploadPercent.value = 0;
showUploadPercent.value = true;
return true;
}
const handleSuccessFile = (response: any, file: UploadFile) => {
showUploadPercent.value = false;
uploadPercent.value = 0;
if (response.code === ResultEnum.SUCCESS) {
ElMessage.success("上传成功");
valFileList.value.push({
name: file.name,
url: response.data.url,
});
emit("update:modelValue", valFileList.value);
return;
} else {
ElMessage.error(response.msg || "上传失败");
}
};
const handleError = (error: any) => {
showUploadPercent.value = false;
uploadPercent.value = 0;
ElMessage.error("上传失败");
};
const customColorMethod = (percentage: number) => {
if (percentage < 30) {
return "#909399";
}
if (percentage < 70) {
return "#375ee8";
}
return "#67c23a";
};
const handleProgress = (event: UploadProgressEvent) => {
uploadPercent.value = event.percent;
};
/**
* 删除文件
*/
function handleRemove(removeFile: UploadUserFile) {
const filePath = removeFile.url;
if (filePath) {
FileAPI.deleteByPath(filePath).then(() => {
// 删除成功回调
valFileList.value = valFileList.value.filter(
(file) => file.url !== filePath
);
emit("update:modelValue", valFileList.value);
});
}
}
/**
* 下载文件
*/
function downloadFile(file: UploadUserFile) {
const filePath = file.url;
if (filePath) {
FileAPI.downloadFile(filePath, file.name);
}
}
</script>
<style lang="scss" scoped>
.el-upload-list__item .el-icon--close {
position: absolute;
top: 50%;
right: 5px;
color: var(--el-text-color-regular);
cursor: pointer;
opacity: 0.75;
transition: opacity var(--el-transition-duration);
transform: translateY(-50%);
}
:deep(.el-upload-list) {
margin: 0;
}
:deep(.el-upload-list__item) {
margin: 0;
}
.show-upload-btn {
:deep(.el-upload) {
display: inline-flex;
}
}
.hide-upload-btn {
:deep(.el-upload) {
display: none;
}
}
</style>
+280
View File
@@ -0,0 +1,280 @@
<!-- 图片上传组件 -->
<template>
<el-upload
v-model:file-list="fileList"
list-type="picture-card"
:class="fileList.length >= props.limit || !props.showUploadBtn ? 'hide' : 'show'"
:action="props.action"
:headers="props.headers"
:data="props.data"
:name="props.name"
:accept="props.accept"
:limit="props.limit"
:disabled="props.disabled"
:auto-upload="false"
:on-change="handleChange"
>
<i-ep-plus />
<template #file="{ file }">
<div style="width: 100%">
<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="previewImg(file)">
<el-icon><zoom-in /></el-icon>
</span>
<span
v-if="props.showDelBtn && !props.disabled"
class="el-upload-list__item-delete"
@click="handleRemove(file)"
>
<el-icon><Delete /></el-icon>
</span>
</span>
</div>
</template>
</el-upload>
<el-image-viewer
v-if="viewVisible"
:zoom-rate="1.2"
@close="closePreview"
:initialIndex="initialIndex"
:url-list="viewFileList"
/>
</template>
<script setup lang="ts">
import { UploadRawFile, UploadUserFile, UploadFile, UploadProps, UploadFiles } from "element-plus";
import FileAPI from "@/api/file";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import { ResultEnum } from "@/enums/ResultEnum";
const emit = defineEmits(["update:modelValue"]);
defineExpose({ handleSubmit });
const props = defineProps({
/**
* 文件路径集合
*/
modelValue: {
type: Array<string>,
default: () => [],
},
/**
* 上传地址
*/
action: {
type: String,
default: "#", //FileAPI.uploadUrl,
},
/**
* 请求头
*/
headers: {
type: Object,
default: () => {
return {
Authorization: localStorage.getItem(TOKEN_KEY),
};
},
},
/**
* 请求携带的额外参数
*/
data: {
type: Object,
default: () => {
return {};
},
},
/**
* 上传文件的参数名
*/
name: {
type: String,
default: "file",
},
/**
* 文件上传数量限制
*/
limit: {
type: Number,
default: 10,
},
/**
* 是否显示删除按钮
*/
showDelBtn: {
type: Boolean,
default: true,
},
/**
* 是否显示上传按钮
*/
showUploadBtn: {
type: Boolean,
default: true,
},
/**
* 单张图片最大大小
*/
uploadMaxSize: {
type: Number,
default: 2 * 1024 * 1024,
},
/**
* 上传文件类型
*/
accept: {
type: String,
default: "image/*",
},
/**
* 是否禁用
*/
disabled: {
type: Boolean,
default: false,
},
});
const viewVisible = ref(false);
const initialIndex = ref(0);
const fileList = ref([] as UploadUserFile[]);
const valFileList = ref([] as string[]);
const viewFileList = ref([] as string[]);
watch(
() => props.modelValue,
(newVal: string[]) => {
const filePaths = fileList.value.map((file) => file.url);
// 监听modelValue文件集合值未变化时,跳过赋值
if (
filePaths.length > 0 &&
filePaths.length === newVal.length &&
filePaths.every((x) => newVal.some((y) => y === x)) &&
newVal.every((y) => filePaths.some((x) => x === y))
) {
return;
}
if (newVal.length <= 0) {
fileList.value = [];
return;
}
fileList.value = newVal.map((filePath) => {
return { url: filePath } as UploadUserFile;
});
valFileList.value = newVal.map((filePath) => {
return filePath;
});
},
{ immediate: true, deep: true }
);
/**
* 上传成功回调
*
* @param options
*/
const handleSuccessFile = (response: any, file: UploadFile) => {
if (response.code === ResultEnum.SUCCESS) {
ElMessage.success("上传成功");
valFileList.value.push(response.data.url);
emit("update:modelValue", valFileList.value);
return;
} else {
ElMessage.error(response.msg || "上传失败");
}
};
const handleChange = (uploadFile: UploadFile) => {
if (uploadFile.raw && uploadFile.size! > props.uploadMaxSize) {
ElMessage.warning("上传图片不能大于" + Math.trunc(props.uploadMaxSize / 1024 / 1024) + "M");
fileList.value = fileList.value.filter((x) => x.url !== uploadFile.url);
return;
}
if (uploadFile.url) {
valFileList.value.push(uploadFile.url);
emit("update:modelValue", valFileList.value);
}
};
const handleError = (error: any) => {
ElMessage.error("上传失败");
};
/**
* 删除图片
*/
function handleRemove(removeFile: UploadFile) {
const filePath = removeFile.url;
if (filePath) {
valFileList.value = valFileList.value.filter((x) => x !== filePath);
// 删除成功回调
emit("update:modelValue", valFileList.value);
}
}
/**
* 限制用户上传文件的格式和大小
*/
function handleBeforeUpload(file: UploadRawFile) {
console.log(file.size);
if (file.size > props.uploadMaxSize) {
ElMessage.warning("上传图片不能大于" + Math.trunc(props.uploadMaxSize / 1024 / 1024) + "M");
return false;
}
return true;
}
async function handleSubmit(type: string) {
for (let i = 0; i < fileList.value.length; i++) {
const file = fileList.value[i];
if (file.raw) {
const res = await FileAPI.upload(file.raw, type);
// console.log(res);
if (res) {
valFileList.value = valFileList.value.filter((x) => x !== file.url);
valFileList.value.push(props.data.prefix + res.url);
emit("update:modelValue", valFileList.value);
} else {
return false;
}
}
}
return true;
}
/**
* 预览图片
*/
const previewImg: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
viewFileList.value = fileList.value.map((file) => file.url!);
initialIndex.value = fileList.value.findIndex((file) => file.url === uploadFile.url);
viewVisible.value = true;
};
/**
* 关闭预览
*/
const closePreview = () => {
viewVisible.value = false;
};
</script>
<style lang="scss" scoped>
.hide {
:deep(.el-upload--picture-card) {
display: none;
}
}
.show {
:deep(.el-upload--picture-card) {
display: flex;
}
}
</style>
+81
View File
@@ -0,0 +1,81 @@
<template>
<div class="editor-wrapper">
<!-- 工具栏 -->
<Toolbar id="toolbar-container" :editor="editorRef" :default-config="toolbarConfig" :mode="mode" />
<!-- 编辑器 -->
<Editor
id="editor-container"
v-model="modelValue"
:default-config="editorConfig"
:mode="mode"
@on-change="handleChange"
@on-created="handleCreated"
/>
</div>
</template>
<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// API 引用
import FileAPI from "@/api/file";
const props = defineProps({
modelValue: {
type: [String],
default: "",
},
mode: {
type: [String],
default: "default",
},
});
const emit = defineEmits(["update:modelValue"]);
const modelValue = useVModel(props, "modelValue", emit);
const editorRef = shallowRef(); // 编辑器实例,必须用 shallowRef
// const mode = ref("default"); // 编辑器模式
const toolbarConfig = ref({}); // 工具条配置
// 编辑器配置
const editorConfig = ref({
placeholder: "请输入内容...",
MENU_CONF: {
uploadImage: {
// 自定义图片上传
async customUpload(file: any, insertFn: any) {
FileAPI.upload(file, "rich-edit").then((data) => {
insertFn(data.url);
});
},
},
},
});
const handleCreated = (editor: any) => {
editorRef.value = editor; // 记录 editor 实例,重要!
};
function handleChange(editor: any) {
modelValue.value = editor.getHtml();
}
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor == null) return;
editor.destroy();
});
</script>
<style>
::v-deep .w-e-text-container {
height: 300px !important;
}
.w-e-text-container .w-e-scroll {
height: 350px !important;
-webkit-overflow-scrolling: touch;
}
</style>