css——background、border、margin、float、content、blur(图片模糊)、user-select:none(禁用用户选择复制),border-image

本文深入讲解CSS中的背景图片设置、边框样式、外边距应用、浮动特性、内容生成及模糊效果等高级技巧,帮助读者掌握更复杂的网页布局与美化方法。

1、background

缩写形式:background:color image repeat 关联方式 position;

 /* img1在最上面,以此类推 */
 background: url(~@/assets/img1.png) no-repeat left top,
    url(~@/assets/img2.png) no-repeat right bottom,
    url(~@/assets/img3.png) no-repeat center center;
  background-size: auto, auto, cover;

可同时设置背景图片和颜色,且图片会覆盖颜色

background-attachment:关联方式

scroll(随滚动条动)
fixed(不随滚动条动)
local(类似scroll,但它的背景图片会跟随内容滚动)

background-repeat:设置背景平铺

repeat : 平铺 (默认)
no-repeat : 不平埔
round : 会将图片缩放后再平铺 (恰好占满 div)
space : 图片不会缩放,只会在图片之间产生相同的间距值 (恰好占满 div)

background-image:url( )选缓存小 可循环的图片平铺 优化性能

背景图片定位:background-position:水平 垂直
(背景图片有定位属性,可以方便控制图片位置。而插入图片语义强,可被搜索引擎收录)

background-size:水平 垂直;设置背景图片尺寸(可以像素 或 百分比)

auto(原始图片大小,默认)
cover(背景图片以等比放大填满父级)
contain(等比放大 一个数值达到最大停止放大)

background-origin:属性规定 background-position 属性相对于什么位置来定位

padding-box(默认值,从padding的位置开始填充背景,会与padding重叠)
border-box(从border的位置开始填充背景,会与border重叠)
content-box(从content的位置开始填充背景,会与content重叠);

background-clip:属性规定背景的绘制区域

padding-box( 显示padding及以内的内容)
border-box(默认值,显示border及以内的内容)
content-box(显示content及以内的内容);

2、border

缩写形式:border:1px solid #ccc;
边框型——border-style:
none 定义无边框。
hidden 与 “none” 相同。不过应用于表时除外,对于表,hidden 用于解决边框冲突。
dotted 定义点状边框。在大多数浏览器中呈现为实线。
dashed 定义虚线。在大多数浏览器中呈现为实线。
solid 定义实线。
double 定义双线。双线的宽度等于 border-width 的值。
groove 定义 3D 凹槽边框。其效果取决于 border-color 的值。
ridge 定义 3D 垄状边框。其效果取决于 border-color 的值。
inset 定义 3D inset 边框。其效果取决于 border-color 的值。
outset 定义 3D outset 边框。其效果取决于 border-color 的值。
inherit 规定应该从父元素继承边框样式。

border-radio:设置圆角

3、margin

外边距margin:横向叠加,竖向合并
盒子水平居中:margin:0 auto;
大小盒子嵌套居中:margin-top时 大小盒子一起改变 可以大盒子加overflow:hidden(更好的是用padding)

4、float

无居中对齐,mg:0 auto;无效
仅可设置fl,fr
不区分block、inline-block、inline
无法撑起盒子高度,如果都float,可能使盒子消失
多盒子顶部对齐可用float
注:先f显示前面,后f显示后面;f位置取决于之前的标准流位置

清除float:

  1. 添加 <div style='clear:both'></div>

优点:通俗易懂
缺点:添加了无意义的标签,不利于后期维护

  1. 使用 br 标签自身属性 <br clear='all'>

优点:代码量少
缺点:同上,不推荐

  1. 父元素设置 overflow: hidden

优点:不存在结构语义化问题,代码量少
缺点:内容增多造成内容隐藏,无法显示溢出元素

  1. 父元素设置 overflow: auto

同上
早期 firefox 有兼容问题

  1. 使用 :after 伪元素
.clearfix {
	*zoom:1; //兼容IE
}

.clearfix::after {
	content:".";
	display:block;
	height:0;
	visibility:hidden;
	clear:both;
}

5、content

content 属性与 :before 及 :after 伪元素配合使用,来插入生成内容。

a:after {content: " (" attr(href) ")";} //在a标签后面插入a标签的链接

none 设置Content,如果指定成Nothing
normal 设置content,如果指定的话,正常,默认是"none"(该是nothing)
counter 设定计数器内容
attr(attribute) 设置Content作为选择器的属性之一。
string 设置Content到你指定的文本
open-quote 设置Content是开口引号
close-quote 设置Content是闭合引号
no-open-quote 如果指定,移除内容的开始引号
no-close-quote 如果指定,移除内容的闭合引号
url(url) 设置某种媒体(图像,声音,视频等内容)
inherit 指定的content属性的值,应该从父元素继承

6、blur

filter:blur(mpx)//m值越大 图片越模糊

7、border-image

边框图片:

border-image-source:可以指定边框图片的路径,默认只是填充到容器的四个角点

border-image-slice:设置四个方向上的裁切距离,fill:做内容的内部填充

border-image-width:边框的宽度,默认是元素的原始边框宽度(注意:1、边框的图片本质是背景,并不会影响元素内容的放置; 2、内容只会受border和padding影响,所以它代替不了border的地位;建议:一般将值设置为原始的边框宽度)

border-image-outset:扩展边框范围,一般用的很少,因为会影响页面布局

border-image-repeat:平铺

stretch(默认值,拉伸)
repeat(直接平铺)
round(将内容缩放后进行完整的重复平铺)

缩写形式 :border-image: source slice/width/outset repeat;

div {
            width: 200px;
            height: 200px;
            border: 30px solid;
            /*border-image-source: url('../images/logo.jpg');
            border-image-slice: 30 fill;
            border-image-width: 30px;
            border-image-outset: 0;
            border-image-repeat: round;*/
            border-image: url("../images/logo.jpg") 27/27px/0 round;
        }

border-image 可以用来做聊天框,不论里面文字多少,整体框都很自然,不会出现背景图片失真的问题

实例:

<style>
		div {
            margin-bottom: 20px;
            height: auto;
            border: 10px solid red;
            /*如果希望内容区域有纹理,可以设置border-image-repeat为repeat或round*/
            /*border-image-source: url("../images/tip.png");
            border-image-slice: 10 fill;
            border-image-width: 10px;*/
            border-image: url("../images/tip.png") 10 fill/27px;
        }

        div:nth-of-type(1) {
            width: 200px;
        }

        div:nth-of-type(2) {
            width: 500px;
        }
</style>

<body>
<div>
    啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!
</div>
<div>
    啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!啦啦啦,我是卖报的小行家,刮风下雨都不怕!
</div>
</body>

在这里插入图片描述

<template> <el-dialog :title="dialogMode === 'create' ? '新建' : dialogMode === 'edit' ? '修改' : '查看'" :visible.sync="dialogVisible" :modal-append-to-body="true" append-to-body :close-on-click-modal="false" custom-class="fixed-height-dialog" width="60%" top="5vh"> <el-form label-width="80px" ref="formRef" :model="currentForm" style="height: 100%; display: flex; flex-direction: column;" :rules="rules"> <!-- 项目信息区域 --> <div class="formBorder"> <el-row :gutter="10"> <el-col :span="6"> <el-form-item size="mini" label="项目名称" prop="projectName"> <el-input v-model="currentForm.projectName" clearable style="width:100%" size="mini" :disabled="dialogMode === 'view'"></el-input> </el-form-item> </el-col> <el-col :span="6"> <el-form-item size="mini" label="项目编号" prop="projectCode"> <el-input v-model="currentForm.projectCode" clearable style="width:100%" size="mini" :disabled="dialogMode === 'view'"></el-input> </el-form-item> </el-col> <el-col :span="12"> <el-form-item size="mini" label="项目周期" prop="projectDate"> <el-date-picker v-model="projectDate" range-separator="→" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期" type="daterange" size="mini" style="width: 100%;" unlink-panels :disabled="dialogMode === 'view'"> </el-date-picker> </el-form-item> </el-col> </el-row> <el-row> <el-col :span="6"> <el-form-item label="负责人" size="mini" style="width: fit-content;"> <el-input v-model="currentForm.projectUser" clearable style="width:100%" size="mini" :disabled="dialogMode === 'view'"></el-input> </el-form-item> </el-col> </el-row> <el-row> <el-col :span="24"> <el-form-item label="项目概述"> <el-input v-model="currentForm.remark" :rows="2" :disabled="dialogMode === 'view'"></el-input> </el-form-item> </el-col> </el-row> </div> <!-- 待检边坡区域 - 使用纯CSS控制高度 --> <div class="formBorder2"> <el-container style="height: 100%;"> <el-header style="height: auto; flex-shrink: 0; padding-bottom: 10px;"> <el-row :gutter="10" type="flex" class="searchDialog"> <el-col :span="5"> <el-select v-model="filterForm.maintenanceCompanyName" placeholder="请选择管养单位" size="mini" clearable filterable @clear="resetSearch" :disabled="dialogMode === 'view'"> <el-option v-for="item in MaintenanceUnitoptions" :key="item.value" :label="item.label" :value="item.value"></el-option> </el-select> </el-col> <el-col :span="5"> <el-select v-model="filterForm.routeCode" placeholder="请选择路线编号" size="mini" clearable filterable @clear="resetSearch" :disabled="dialogMode === 'view'"> <el-option v-for="item in routeCodeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option> </el-select> </el-col> <el-col :span="5"> <el-input v-model="filterForm.searchKey" placeholder="请输入边坡编号或名称" size="mini" clearable @keyup.enter.native="searchForm" @clear="resetSearch" :disabled="dialogMode === 'view'"> <i slot="suffix" class="el-input__icon el-icon-search"></i> </el-input> </el-col> <el-col :span="5"> <el-select v-model="filterForm.evaluateLevel" placeholder="请选择技术状态等级" size="mini" clearable @clear="resetSearch" :disabled="dialogMode === 'view'"> <el-option v-for="item in evaluateLeveloptions" :key="item.value" :label="item.label" :value="item.value" /> </el-select> </el-col> <el-col :span="2" :offset="4"> <el-button type="primary" size="mini" style="width:100%" icon="el-icon-search" @click="searchForm" :loading="loading" :disabled="dialogMode === 'view'">搜索</el-button> </el-col> </el-row> </el-header> <!-- 边坡表格 - 移除动态高度绑定 --> <el-main style="overflow-y: hidden;"> <el-table ref="scrollTable" v-loading="loading" style="width: 100%;" border :data="formTabledata" :row-style="{ height: '36px' }" :cell-style="{ padding: '4px 0', textAlign: 'center' }" :header-cell-style="{ height: '36px', padding: '4px 0', lineHeight: '36px', textAlign: 'center' }" @selection-change="handleSelectionChange" :row-key="getRowkey"> <!-- 选择列(查看模式禁用--> <el-table-column type="selection" width="55" :selectable="isRowSelectable" :reserve-selection="true"> </el-table-column> <!-- 其他数据列 --> <el-table-column label="管养单位" prop="maintenanceCompanyName" width="290" show-overflow-tooltip></el-table-column> <el-table-column label="路线编号" prop="routeCode" width="100"></el-table-column> <el-table-column label="边坡编号" prop="sideSlopeCode" width="240" show-overflow-tooltip></el-table-column> <el-table-column label="边坡名称" prop="sideSlopeName" width="267" show-overflow-tooltip></el-table-column> <el-table-column label="技术状态等级" width="137"> <template slot-scope="scope"> {{ mapEvaluateLevel(scope.row.evaluateLevel) }} </template> </el-table-column> </el-table> </el-main> <!-- 分页区域 --> <el-footer style="flex-shrink: 0; padding-top: 10px;"> <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageParams.pageNo" :page-sizes="[10, 20, 50, 100]" :page-size="pageParams.pageSize" layout="total, prev, pager, next" :total="total"> </el-pagination> </el-footer> </el-container> </div> </el-form> <!-- 弹窗底部按钮 --> <div slot="footer" class="dialog-footer" v-if="dialogMode === 'create' || dialogMode === 'edit'"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="submitForm">提交</el-button> </div> </el-dialog> </template> <script> import { mapCfg } from "@/utils"; import { getPeriodicInspectionSideSlopePageList, addPeriodicInspection, modifyPeriodicInspection, getSelectedPeriodicInspectionSideSlopeList } from "../../api/testProject"; import { getMaintenanceCompanyList, getRouteList } from "../../api/basicInformation"; export default { name: "SideSlopeDialog", props: { visible: Boolean, // 控制弹窗显示 mode: String, // 模式:create/edit/view initialForm: Object, // 初始表单数据 }, data() { return { isInitializingSelection: false, // 初始化状态标志 dialogVisible: this.visible, // 弹窗显示状态 dialogMode: this.mode, // 当前模式 currentForm: { ...this.initialForm }, // 当前表单数据 projectDate: [], // 项目日期范围 total: 0, // 总数据量 loading: false, // 加载状态 pageParams: { // 分页参数 pageNo: 1, pageSize: 10, }, filterForm: { // 搜索条件 maintenanceCompanyName: "", routeCode: "", searchKey: "", evaluateLevel: "", }, mulitipleSelection: [], allSelection: new Map(), MaintenanceUnitoptions: [], // 管养单位选项 routeCodeOptions: [], // 路线编号选项 formTabledata: [], // 表格数据 evaluateLeveloptions: [], // 技术状态等级选项 rules: { // 表单验证规则 projectName: [ { required: true, message: "项目名称不能为空", trigger: "blur" }, ], projectCode: [ { required: true, message: "项目编码不能为空", trigger: "blur" }, ], }, }; }, watch: { // 修复1:监听visible变化时确保加载数据 async visible(val) { this.dialogVisible = val; if (val) { // 打开对话框时重置状态 this.resetAllData(); // 关键修复:确保在创建模式外加载数据 if (this.dialogMode !== 'create' && this.currentForm.id) { // 确保在DOM更新后加载数据 await this.$nextTick(); await this.LoadListData(); } } else { // 关闭对话框时重置数据 this.resetAllData(); } }, // 修复2:监听模式变化 mode(val) { this.dialogMode = val; // 当模式从创建变为编辑/查看时,确保加载数据 if (this.dialogVisible && val !== 'create' && this.currentForm.id) { this.LoadListData(); } }, // 修复3:监听初始表单数据变化 initialForm: { deep: true, immediate: true, // 添加立即执行 async handler(val) { this.currentForm = { ...val }; this.projectDate = [val.projectStartDate, val.projectEndDate]; // 关键修复:当初始表单有ID时立即加载数据 if (this.dialogVisible && val.id && this.dialogMode !== 'create') { await this.$nextTick(); await this.LoadListData(); } } }, // 同步弹窗显示状态到父组件 dialogVisible(val) { this.$emit("update:visible", val); }, projectDate: { deep: true, handler(value) { if (value && value.length === 2) { this.currentForm.projectStartDate = value[0]; this.currentForm.projectEndDate = value[1]; } }, }, }, async created() { // 初始化数据 this.getRouteList(); await this.getEvaluateLevel(); this.getMaintenanceCompanyList(); }, methods: { handleSelectionChange(selection) { // 跳过初始化阶段的选中状态变更 if (this.isInitializingSelection) return; // 获取当前页选中项的key集合 const currentPageKeys = new Set( selection.map(row => row.sideSlopeUniqueCode) ); // 处理当前页的取消选中操作 this.formTabledata.forEach(row => { const key = row.sideSlopeUniqueCode; // 仅当行在全局选中池中但不在当前页选中集合时删除 if (this.allSelection.has(key) && !currentPageKeys.has(key)) { this.allSelection.delete(key); } }); // 添加新选中的项到全局池 selection.forEach(row => { const key = row.sideSlopeUniqueCode; if (!this.allSelection.has(key)) { this.allSelection.set(key, row); } }); // 更新当前页选中引用 this.mulitipleSelection = selection; }, getRowkey(row) { return row.sideSlopeUniqueCode; }, // 判断行是否可选(查看模式禁用选择) isRowSelectable(row, index) { return this.dialogMode !== "view"; }, // 获取管养单位列表 async getMaintenanceCompanyList() { const res = await getMaintenanceCompanyList(); this.MaintenanceUnitoptions = res.map((item) => ({ value: item, label: item, })); }, // 获取路线列表 async getRouteList() { const res = await getRouteList(); this.routeCodeOptions = res.map((item) => ({ value: item.id, label: item.routeCode, })); }, // 搜索方法 searchForm() { // this.showSelectedOnly = false, this.pageParams.pageNo = 1; this.LoadListData(); }, // 重置搜索条件 resetSearch() { // this.showSelectedOnly = true, this.filterForm = { maintenanceCompanyName: "", routeCode: "", searchKey: "", evaluateLevel: "", }; this.pageParams.pageNo = 1; this.LoadListData(); }, // 重置组件状态 resetAllData() { this.resetSelection(); this.formTabledata = []; // 清空表格数据 this.total = 0; // 重置总条数 this.pageParams = { // 重置分页 pageNo: 1, pageSize: 10 }; // 重置搜索条件(可选) this.filterForm = { maintenanceCompanyName: "", routeCode: "", searchKey: "", evaluateLevel: "" }; }, // 修改原有方法 resetSelection() { this.allSelection.clear(); this.allSelection = new Map(); if (this.$refs.scrollTable) { this.$refs.scrollTable.clearSelection(); } }, // 映射技术状态等级 mapEvaluateLevel(level) { const option = this.evaluateLeveloptions.find( (item) => item.value === level ); return option.label; }, // 加载表格数据 async LoadListData() { this.loading = true; try { const params = { orgId: this.filterForm.maintenanceCompanyName, routeId: this.filterForm.routeCode, searchKey: this.filterForm.searchKey, evaluateLevel: this.filterForm.evaluateLevel, pageSize: this.pageParams.pageSize, pageNo: this.pageParams.pageNo, }; // 获取表格数据 const res = await getPeriodicInspectionSideSlopePageList(params); this.formTabledata = res.entities; this.total = res.entityCount; // 处理非创建模式的数据加载 if (this.dialogMode !== 'create' && this.currentForm.id) { // 首次加载时获取所有选中项 if (this.pageParams.pageNo === 1) { const selected = await getSelectedPeriodicInspectionSideSlopeList({ periodicId: this.currentForm.id, pageSize: 10000, // 获取所有选中项 pageNo: 1 }); // 重置全局选中池 this.allSelection.clear(); this.mulitipleSelection = selected.entities; // 存储全局选中状态 this.mulitipleSelection.forEach(item => { this.allSelection.set(item.sideSlopeUniqueCode, item); }); } // 设置当前页选中状态 this.isInitializingSelection = true; this.$nextTick(() => { this.formTabledata.forEach(row => { if (this.allSelection.has(row.sideSlopeUniqueCode)) { this.$refs.scrollTable.toggleRowSelection(row, true); } }); this.isInitializingSelection = false; }); } } catch (error) { console.error("加载数据失败:", error); this.$message.error("加载数据失败"); } finally { this.loading = false; } }, // 分页大小变化 handleSizeChange(val) { this.pageParams.pageSize = val; this.pageParams.pageNo = 1; this.LoadListData(); }, // 当前页码变化 handleCurrentChange(val) { this.pageParams.pageNo = val; this.LoadListData(); }, // 获取技术状态等级选项 async getEvaluateLevel() { const levelList = await mapCfg("Inspection.Regular.RegularEvaluateLevel")(); this.evaluateLeveloptions = levelList.map((item) => ({ value: item.key, label: item.value, })); }, // 提交表单 async submitForm() { this.$refs.formRef.validate(async (valid) => { if (valid) { // 验证是否选择了边坡 const selectedItems = Array.from(this.allSelection.values()); if (this.allSelection.size === 0) { this.$message.warning("请至少选择一个边坡"); return; } // 构造提交参数 const params = { ...this.currentForm, sideSlopeDetailList: selectedItems.map(item => ({ sideSlopeUniqueCode: item.sideSlopeUniqueCode, evaluateLevel: item.evaluateLevel, evaluateDate: item.evaluateDate || undefined })), }; // 根据模式选择操作 const action = this.dialogMode === "create" ? addPeriodicInspection : modifyPeriodicInspection; // 执行操作 try { const success = await action(params); if (success) { this.$message.success( this.dialogMode === "create" ? "新建成功" : "修改成功" ); this.$refs.scrollTable.clearSelection(); this.$emit("success"); this.dialogVisible = false; } else { this.$message.error("操作失败"); } } catch (error) { this.$message.error(error.message || "操作失败"); } } }); } }, }; </script> <style lang="scss" scoped> /* 修复1:弹性容器最小高度约束 */ :deep(.fixed-height-dialog), .formBorder2, .formBorder2 .el-container, .formBorder2 .el-main { min-height: 0 !important; } /* 表格行高优化 */ :deep(.el-table) { .el-table__row { height: 36px !important; td { padding: 4px 0 !important; } } .el-table__header { th { padding: 4px 0 !important; .cell { line-height: 28px !important; } } } /* 确保内部滚动 */ .el-table__body-wrapper { overflow-y: auto !important; max-height: calc(100vh - 400px) !important; } } /* 表单区域固定 */ .formBorder { position: relative; ///为伪元素提供定位上下文 border: thin dotted black !important; padding: 10px !important; margin-top: 15px !important; flex-shrink: 0 !important; height: auto !important; overflow: visible !important; margin-bottom: 15px !important; /* 边框的文字 */ &::before { content: "项目信息"; position: absolute; top: -8px; //调整到更合适的位置 left: 15px; //向右移动避免遮挡 background-color: #fff; //背景色需与页面背景一致 padding: 0 8px; font-size: 13px; color: #606266; z-index: 10; //提高层级确保显示 font-weight: 500; //加粗文字 pointer-events: none; //防止点击穿透 } } .formBorder2 { position: relative; border: thin dotted black; padding: 10px; flex: 1; min-height: 0; overflow: hidden; // 保留 display: flex; flex-direction: column; margin-top: 15px; &::before { content: "待检边坡"; position: absolute; top: -8px; //调整到更合适的位置 left: 15px; //向右移动避免遮挡 background-color: #fff; //背景色需与页面背景一致 padding: 0 8px; font-size: 13px; color: #606266; z-index: 10; //提高层级确保显示 font-weight: 500; //加粗文字 pointer-events: none; //防止点击穿透 } .el-container { height: auto !important; // 覆盖行内样式 flex: 1; // 填满剩余空间 display: flex; flex-direction: column; min-height: 0; .el-header { flex-shrink: 0; height: auto !important; padding-bottom: 10px; } .el-main { flex: 1; overflow: hidden; position: relative; padding: 0; } .el-footer { flex-shrink: 0; padding-top: 10px; } } } // 弹窗底部按钮区域 .dialog-footer { padding: 10px 20px; border-top: 1px solid #ebeef5; text-align: center; } // 搜索区域样式 .searchDialog { margin-top: 5px; } // 空数据样式 :deep(.el-table__empty-block) { min-height: 200px; display: flex; justify-content: center; align-items: center; } // 分页样式 :deep(.el-pagination) { padding: 5px 0; } // 表格高度控制 :deep(.el-table) { height: 100% !important; .el-table__body-wrapper { overflow-y: auto !important; } } </style>为什么待检边坡有一半被margin-top遮住了
最新发布
08-29
<template> <el-form ref="ruleFormRef" style="margin-top: 20px;max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto" :disabled="pageMode === 'view'"> <el-form-item label="产品名称:" prop="name"> <el-input v-model="ruleForm.name" /> </el-form-item> <el-form-item label="产品描述:" prop="description"> <el-input v-model="ruleForm.description" type="textarea"/> </el-form-item> <el-form-item label="产品分类:" prop="category" style="width: 50%;"> <el-select v-model="ruleForm.category" placeholder="请选择分类"> <el-option v-for="item in categorys" :label="item.name" :value="item.id" :key="item.id" /> </el-select> </el-form-item> <el-form-item label="产品单价:" prop="price"> <el-input v-model.number="ruleForm.price" type="number" style="width: 240px" /> </el-form-item> <el-form-item label="产品库存:" prop="stock"> <el-input v-model.number="ruleForm.stock" type="number" style="width: 240px" /> </el-form-item> <el-form-item label="生产厂家:" prop="manufacturer"> <el-input v-model="ruleForm.manufacturer" /> </el-form-item> <el-form-item label="产地:" required> <el-col :span="12"> <el-form-item prop="originProvince"> <el-select v-model="ruleForm.originProvince" placeholder="省" style="flex: 1; margin-right: 10px"> <el-option v-for="item in originProvinces" :key="item.id" :label="item.name" :value="item.id" /> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item prop="originCity"> <el-select v-model="ruleForm.originCity" placeholder="市" style="flex: 1 " :disabled="!ruleForm.originProvince"> <el-option v-for="item in originCitys" :key="item.id" :label="item.name" :value="item.id" /> </el-select> </el-form-item> </el-col> </el-form-item> <el-form-item label="发货地:" required> <el-col :span="12"> <el-form-item prop="shippingProvince"> <el-select v-model="ruleForm.shippingProvince" placeholder="省" style="flex: 1; margin-right: 10px"> <el-option v-for="item in originProvinces" :key="item.id" :label="item.name" :value="item.id" /> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item prop="shippingCity"> <el-select v-model="ruleForm.shippingCity" placeholder="市" style="flex: 1" :disabled="!ruleForm.shippingProvince"> <el-option v-for="item in shippingCities" :key="item.id" :label="item.name" :value="item.id" /> </el-select> </el-form-item> </el-col> </el-form-item> <el-form-item label="生产日期" required> <el-col :span="11"> <el-form-item prop="createAt"> <el-date-picker v-model="ruleForm.createAt" type="date" aria-label="Pick a date" placeholder="Pick a date" style="width: 100%" /> </el-form-item> </el-col> </el-form-item> <el-form-item> <!-- 登录按钮:仅在默认模式下显示 --> <el-button v-if="pageMode === 'default'" style="margin-left: 18px;" type="primary" @click="submitForm(ruleFormRef, ruleForm)"> 登录 </el-button> <!-- 更新按钮:仅在编辑模式下显示 --> <el-button v-if="pageMode === 'edit'" style="margin-left: 30px;" type="primary" @click="updateForm(ruleFormRef)"> 更新 </el-button> <!-- 重置按钮:在编辑或默认模式下都显示 --> <el-button v-if="pageMode === 'edit' || pageMode === 'default'" style="margin-left: 30px;" type="primary" @click="resetForm(ruleFormRef)"> 重置 </el-button> </el-form-item> </el-form> </template> <script setup> import { ref, reactive, onMounted } from 'vue'; import productApi from '@/api/products' import placeApi from '@/api/place' import { useRouter } from 'vue-router' import { ElLoading, ElMessage } from 'element-plus' const pageMode = ref('') // 可选值: 'view', 'edit', 'default' const router = useRouter(); const ruleFormRef = ref() const categorys = ref([])// 产品分类 const originProvinces = ref([]) // 省份数据 const originCitys = ref([]) // 城市数据 const shippingCities = ref([]) // 发货地城市数据 const ruleForm = reactive({ name: '', description: '', category: '', price: '', stock: '', manufacturer: '', originProvince: '', originCity: '', shippingProvince: '', shippingCity: '', createAt: '', user: 'aaa', delivery: false, type: [], }) const rules = reactive({ name: [ { required: true, message: '请输入产品名称', trigger: 'blur' }, { max: 10, message: '长度超过10位', trigger: 'blur' }, ], description: [ { required: true, message: '请输入产品描述', trigger: 'blur' }, { max: 200, message: '长度超过200位', trigger: 'blur' }, ], category: [ { required: true, message: '请选择产品分类', trigger: 'change', }, ], price: [ { required: true, message: '请输入产品单价', trigger: ['blur', 'change'] }, { validator: (rule, value, callback) => { if (value === null || value === '') { callback(new Error('请输入产品单价')) } else if (value <= 0) { callback(new Error('单价必须大于 0')) } else if (value > 10000) { callback(new Error('单价不能大于 10000')) } else { callback() } }, trigger: ['blur', 'change'] } ], stock: [ { required: true, message: '请输入产品库存', trigger: ['blur', 'change'] }, { validator: (rule, value, callback) => { if (value === null || value === '') { callback(new Error('请输入商品单价')) } else if (value <= 0) { callback(new Error('单价必须大于 0')) } else if (value > 10000) { callback(new Error('单价不能大于 10000')) } else { callback() } }, trigger: ['blur', 'change'] } ], manufacturer: [ { required: true, message: '请输入生产厂家', trigger: 'blur' }, ], originProvince: { validator: (rule, value, callback) => { if (!value) { callback(new Error('请选择产地省份')) } else { callback() } }, trigger: 'change' }, originCity:{ validator: (rule, value, callback) => { if (!value) { callback(new Error('请选择产地城市')) } else { callback() } }, trigger: 'change' }, shippingProvince: { validator: (rule, value, callback) => { if (!value) { callback(new Error('请选择发货省份')) } else { callback() } }, trigger: 'change' }, shippingCity:{ validator: (rule, value, callback) => { if (!value) { callback(new Error('请选择发货城市')) } else { callback() } }, trigger: 'change' }, createAt: [ { type: 'date', required: true, message: '请输入日期', trigger: 'change', }, ], }) // 重置表单操作 const resetForm = (formEl) => { if (!formEl) return formEl.resetFields() } //产品分类 function getCategory() { productApi.getCategory().then(res => { categorys.value = res.data; }) } // 获取商品详情 function getProductDetail(productId) { productApi.getById(productId).then(res => { const data = res.data // 先赋值整个对象 Object.assign(ruleForm, data) }).catch(error => { console.error('获取商品详情失败:', error); }); } // 获取省份 function getProvinces() { placeApi.getProvince().then(res => { originProvinces.value = res.data }).catch(error => { console.error('获取省份失败:', error) }) } // 监听产地省份变化,加载城市 watch( () => ruleForm.originProvince, (newVal) => { if (newVal) { placeApi.getCity(newVal).then(res => { originCitys.value = res.data }).catch(() => { originCitys.value = [] }) } else { // 如果省份为空,则清空城市列表和当前选中的城市字段 originCitys.value = [] ruleForm.originCity = '' } } ) // 监听发货地省份变化,加载城市 watch( () => ruleForm.shippingProvince, (newVal) => { if (newVal) { placeApi.getCity(newVal).then(res => { shippingCities.value = res.data }).catch(() => { shippingCities.value = [] }) } else { // 如果省份为空,则清空城市列表和当前选中的城市字段 shippingCities.value = [] ruleForm.shippingCity = '' } } ) // 更新操作 const updateForm = async (formEl) => { if (!formEl) return const loading = ElLoading.service({ fullscreen: true }) await formEl.validate((valid, fields) => { if (valid) { console.log('开始提交...') // 调用 API 更新商品信息 productApi.update(ruleForm).then(res => { ElMessage.success('更新成功') router.push('/home/test1') // 可选跳转回列表页 }).catch(error => { console.error('更新失败:', error) ElMessage.error('更新失败,请重试') }).finally(() => { loading.close() }) } else { console.log('表单验证失败:', fields) ElMessage.error('请检查输入内容') loading.close() return false } }) } // 登录操作 const submitForm = async (formEl, ruleForm) => { if (!formEl) return await formEl.validate((valid, fields) => { if (valid) { console.log('开始提交商品...') const loading = ElLoading.service({ fullscreen: true }) productApi.addProduct(ruleForm).then(res => { ElMessage.success('登录成功') router.push('/home/test1') }).catch(error => { console.error('登录失败:', error) ElMessage.error('登录失败,请重试') }).finally(() => { loading.close() }) } else { console.log('表单验证失败:', fields) ElMessage.error('请检查输入内容') loading.close() return false } }) } onMounted(() => { getCategory() getProvinces() // 获取当前路由信息 const route = router.currentRoute.value // 判断页面是查看、编辑还是新增模式 const type = route.query.type const productId = route.params.id || route.query.id if (type === 'view') { pageMode.value = 'view' // 查看模式:不显示按钮 } else if (type === 'edit') { pageMode.value = 'edit' // 编辑模式:显示“更新”、“重置” } else { pageMode.value = 'default' // 默认模式:显示“登录”、“重置” } // 如果存在商品 ID,则调用接口获取商品详情并填充表单 if (productId) { getProductDetail(productId) } }) </script> <style> .location-selectors { display: flex; justify-content: space-between; width: 100%; } </style>  现在我想不用element组件写,我想自己写子组件实现表单的同样的样式和功能
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值