转载-<div>并排显示实例

本文介绍了几种常见的CSS布局方法,包括使用display的inline属性、float属性实现div并排显示,以及实现左边为绝对宽度、右边为相对宽度的布局方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接:http://gaojianqi6.iteye.com/blog/1446651


一、使用display的inline属性

Html代码  收藏代码
  1. <div style="width:300px; height:auto; float:left; display:inline">AAAA</div>  
  2.   
  3. <div style="width:300px; height:auto; float:left; display:inline">BBBB</div>  

二、通过设置float来让Div并排显示

Html代码  收藏代码
  1. <style>  
  2. #left,#right   {float:left;border:1px   solid   red;   padding:10px;}  
  3. </style>  
  4. <div   id"main ">  
  5.     <div   id"left "> 1111 </div>  
  6.     <div   id"right "> 2222 <br> 2222 <br> 2222 </div>  
  7.     <!-- 如果不用clear屬性可能會出現瀏覽器不兼容問題,clear設這元素周圍沒有浮動元素 -->  
  8.     <div   style="clear:both"></div>  
  9.  </div>   

三、对于两个div并排,左边为绝对宽度,右边为相对宽度的,需要用到这种布局的情况比较多见,如左边为导航,右边为内容的页面

    1、将最大的容器padding-left固定宽度,左边的固定宽度的一块position:absolute,然后right的一块width为百分百

    2、 使用position:absolute。代码如下。

 

Html代码  收藏代码
  1. <style>  
  2. body{ margin:0; height:100%}  
  3. html{ height:100%} /*兼容firefox的div高度100%*/  
  4. #left{ position:absolute; top:0; left:0; width:200px; height:100%; background-color:#CCCCCC}  
  5. #right{ margin-left:200px; height:100%; background-color:#0099FF}  
  6. </style>  
  7. <div id="left">left</div>  
  8. <div id="right">right</div>  

  这段代码主要涉及到以下两点点比较重要的:

 (1)兼容firefox实现div高度100%;
 (2)div绝对定位的妙用;在页面布局的时候,position:absolute如果灵活的应用,可以达到很好的效果。


  3、 使用float解决div左右布局,左为绝对宽度,右为相对宽度问题

Html代码  收藏代码
  1. <style type="text/css">  
  2. body{ margin:0; height:100% }  
  3. html{ height:100% }  
  4. #left{ width:150px; height:100%; float:left; _margin-right:-3px; background-color: yellow }  
  5. #main{ height:100%; background-color: green }  
  6. </style>  
  7.   
  8. <div id="left"></div>  
  9. <div id="main"></div>  

 4、代码如下。方法3可能没有按照题目要求,但是可以达到一样的页面效果。主要是使用了div的float属性。

 

Html代码  收藏代码
  1. <style>  
  2. body{ margin:0; height:100%}  
  3. html{ height:100%} /*兼容firefox的div高度100%*/  
  4. #left{ width:200px; height:100%; background-color:#CCCCCC; float:left}  
  5. #main{ width:100%; height:100%; background-color:#0099FF}  
  6. </style>  
  7. <div id="main">  
  8. <div id="left">left</div>  
  9. Right  
  10. </div>  
<template> <el-container class="layout-container-demo" style="height: 500px"> <el-header style="text-align: right; font-size: 12px"> <div class="toolbar"> <el-dropdown> <el-icon style="margin-right: 8px; margin-top: 1px"> <setting /> </el-icon> <template #dropdown> <el-dropdown-menu> <el-dropdown-item @click="logOut()">退出登录</el-dropdown-item> </el-dropdown-menu> </template> </el-dropdown> <span>关宇航</span> </div> </el-header> <el-container> <el-aside width="200px"> <el-scrollbar> <el-menu :default-active="$route.path" class="el-menu-vertical-demo" :router="true"> <template v-for="(item, index) in menuList"> <el-menu-item v-if="isShow(item)" :index="index" :route="item.path">{{ item.label }}</el-menu-item> </template> </el-menu> </el-scrollbar> </el-aside> <el-main> <router-view /> </el-main> </el-container> </el-container> </template> <script setup> import { Menu as IconMenu, Setting } from '@element-plus/icons-vue' import useUserStore from '@/store/modules/user'; import { ElMessage } from 'element-plus' const userStore = useUserStore(); const router = useRouter(); const menuList = ref([]); function isShow(item) { return item?.aaaaa != 'asaf' } onMounted(() => { if (userStore.isLogin()) { setMenu(router.options.routes); } else { ElMessage.error(‘用户未登录,跳转至登录页面’); router.push(‘/’); } }); function setMenu(routes) { const menu = []; for (const route of routes) { if (route.children) { for (const child of route.children) { if (child.meta && child.meta.title) { const menuItem = { index: child.path, path: route.path + ‘/’ + child.path, label: child.meta.title, aaaaa: child.meta.aaaaa, }; menu.push(menuItem); } } } } menuList.value = menu } function logOut() { userStore.logOut(); ElMessage.success(‘已退出登录’); router.push(‘/’); } </script> <style scoped> .layout-container-demo .el-header { position: relative; background-color: var(--el-color-primary-light-7); color: var(--el-text-color-primary); } .layout-container-demo .el-aside { color: var(--el-text-color-primary); background: var(--el-color-primary-light-8); height: 100vh; } .layout-container-demo .el-menu { border-right: none; } .layout-container-demo .el-main { padding: 0; } .layout-container-demo .toolbar { display: inline-flex; align-items: center; justify-content: center; height: 100%; right: 20px; } </style> 我想把 用户管理画面,项目一览画面,项目管理画面 ,障碍票一览画面,障碍票详细画面 加入上部导航栏中,然后在丰富一下画面内容 用<template>画
07-23
<script setup> // import { h } from 'snabbdom' import { onBeforeUnmount, ref, shallowRef } from 'vue' // import { IButtonMenu } from '@wangeditor/core' import { Boot } from '@wangeditor/editor' import { Editor, Toolbar } from '@wangeditor/editor-for-vue' // 测试:第三方插件 // import withCtrlEnter from '@wangeditor/plugin-ctrl-enter' // Boot.registerPlugin(withCtrlEnter) // // 测试:多语言 // i18nChangeLanguage('en') // // 测试:注册 renderElem // function renderElemFn(elem, children) { // const vnode = h('div', {}, children) // type: 'paragraph' 节点,即渲染为 <p> 标签 // return vnode // } // const renderElemConf = { // type: 'paragraph', // 节点 type ,重要!!! // renderElem: renderElemFn, // } // Boot.registerRenderElem(renderElemConf) // // 测试:注册插件 // function withCtrlEnter(editor) { // const { insertBreak } = editor // setTimeout(() => { // // beforeInput 事件不能识别 ctrl+enter ,所以自己绑定 DOM 事件 // const { $textArea } = DomEditor.getTextarea(newEditor) // $textArea.on('keydown', e => { // const isCtrl = e.ctrlKey || e.metaKey // if (e.keyCode === 13 && isCtrl) { // // ctrl+enter 触发换行 // editor.insertBreak() // } // }) // }) // const newEditor = editor // newEditor.insertBreak = () => { // const e = window.event // const isCtrl = e.ctrlKey || e.metaKey // // 只有 ctrl 才能换行 // if (isCtrl) { // insertBreak() // } // } // return newEditor // } // Boot.registerPlugin(withCtrlEnter) // 测试:注册 button menu // class MyButtonMenu { // constructor() { // // this.title = '', // this.tag = 'button' // } // getValue() { return '' } // isActive() { return false } // isDisabled() { return false } // exec(editor) { // console.log(editor) // // alert('menu1 exec') // } // } // const menuConf = { // key: 'my-menu-1', // menu key ,唯一。注册之后,需通过 toolbarKeys 配置到工具栏 // factory() { // return new MyButtonMenu() // }, // } // // 检查菜单是否已注册,避免重复注册 // if (!Boot.getMenuConfig('my-menu-1')) { // Boot.registerMenu(menuConf); // console.log('菜单注册成功'); // } else { // console.log('菜单已存在,跳过注册'); // } // console.log(1111111111) // 移到组件最外层,确保模块加载时只执行一次 class MyButtonMenu { constructor() { this.title = ''; // 必须有标题,否则按钮不显示 this.tag = 'button'; } getValue() { return ''; } isActive() { return false; } isDisabled() { return false; } exec(editor) { // console.log('自定义菜单点击', editor); // editor.insertText('这是自定义菜单插入的内容'); // 示例功能 } } const menuConf = { key: 'my-menu-1', factory() { return new MyButtonMenu(); }, }; // 核心:用try-catch捕获重复注册错误 try { Boot.registerMenu(menuConf); console.log('菜单注册成功'); } catch (err) { if (err.message.includes('Duplicated key')) { console.log('菜单已注册,跳过重复注册'); } else { console.error('菜单注册失败:', err); } } // 编辑器实例,必须用 shallowRef ,重要! const editorRef = shallowRef() // 内容 HTML const valueHtml = ref('<p>hello world</p>') // 编辑器配置 const editorConfig = { placeholder: '请输入内容...', MENU_CONF: { insertImage: { checkImage(src) { console.log('image src', src) if (src.indexOf("http") !== 0) { return "图片网址必须以 http/https 开头"; } return true; }, }, } } // 工具栏配置 const toolbarConfig = { // toolbarKeys: ['headerSelect', 'bold', 'my-menu-1'], // excludeKeys: [], insertKeys: { index: 0, keys: 'my-menu-1' } } // 编辑器回调函数 const handleCreated = (editor) => { console.log("created", editor); editorRef.value = editor // 记录 editor 实例,重要! // window.editor = editor // 临时测试使用,用完删除 } const handleChange = (editor) => { console.log("change:", editor.children); } const handleDestroyed = (editor) => { console.log('destroyed', editor) } const handleFocus = (editor) => { console.log('focus', editor) } const handleBlur = (editor) => { console.log('blur', editor) } const customAlert = (info, type) => { alert(`【自定义提示】${type} - ${info}`) } const customPaste = (editor, event, callback) => { console.log('ClipboardEvent 粘贴事件对象', event) // 自定义插入内容 editor.insertText('xxx') // 返回值(注意,vue 事件的返回值,不能用 return) callback(false) // 返回 false ,阻止默认粘贴行为 // callback(true) // 返回 true ,继续默认的粘贴行为 } // 及时销毁编辑器 onBeforeUnmount(() => { const editor = editorRef.value if (editor == null) return // 销毁,并移除 editor editor.destroy() }) const getHtml = () => { const editor = editorRef.value if (editor == null) return console.log(editor.getHtml()) } </script> <template> <!-- <div>--> <!-- <button @click="getHtml">获取 html</button>--> <!-- </div>--> <!-- <div style="border: 1px solid #ccc">--> <!-- <!– 工具栏 –>--> <!-- <Toolbar--> <!-- :editor="editorRef"--> <!-- :defaultConfig="toolbarConfig"--> <!-- style="border-bottom: 1px solid #ccc"--> <!-- />--> <!-- <!– 编辑器 –>--> <!-- <Editor--> <!-- v-model="valueHtml"--> <!-- :defaultConfig="editorConfig"--> <!-- @onChange="handleChange"--> <!-- @onCreated="handleCreated"--> <!-- @onDestroyed="handleDestroyed"--> <!-- @onFocus="handleFocus"--> <!-- @onBlur="handleBlur"--> <!-- @customAlert="customAlert"--> <!-- @customPaste="customPaste"--> <!-- style="height: 500px"--> <!-- />--> <!-- </div>--> <div class="editor-container"> <!-- 添加容器类名 --> <!-- 工具栏 --> <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" style="border-bottom: 1px solid #e5e7eb" /> <!-- 编辑器 --> <Editor v-model="valueHtml" :defaultConfig="editorConfig" @onChange="handleChange" @onCreated="handleCreated" @onDestroyed="handleDestroyed" @onFocus="handleFocus" @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" /> </div> </template> <style src="@wangeditor/editor/dist/css/style.css"> /* 编辑器整体容器 */ .editor-container { border: 1px solid #e5e7eb; /* 浅灰色边框 */ border-radius: 8px; /* 圆角 */ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 轻微阴影 */ overflow: hidden; /* 防止内部元素溢出 */ transition: box-shadow 0.2s ease; /* 阴影过渡效果 */ } .editor-container:hover { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* hover时增强阴影 */ } /* 工具栏样式 */ .w-e-toolbar { background-color: #f9fafb !important; /* 工具栏背景色 */ border-bottom: 1px solid #e5e7eb !important; /* 底部边框 */ padding: 8px 12px !important; /* 内边距 */ } /* 工具栏按钮通用样式 */ .w-e-toolbar .w-e-menu { margin: 0 3px !important; /* 按钮间距 */ border-radius: 4px !important; /* 按钮圆角 */ transition: all 0.2s ease !important; /* 过渡效果 */ } .w-e-toolbar .w-e-menu:hover { background-color: #eef2f5 !important; /* 悬停背景色 */ transform: translateY(-1px) !important; /* 轻微上浮效果 */ } /* 自定义菜单按钮样式(my-menu-1) */ .w-e-toolbar [data-key="my-menu-1"] { background-color: #4f46e5 !important; /* 紫色背景(突出自定义按钮) */ color: white !important; /* 白色文字 */ border: none !important; } .w-e-toolbar [data-key="my-menu-1"]:hover { background-color: #4338ca !important; /* 深色hover效果 */ } /* 编辑区域样式 */ .w-e-text-container { height: 500px !important; /* 固定高度 */ padding: 16px !important; /* 内边距 */ background-color: white !important; /* 白色背景 */ } /* 编辑区域内容样式 */ .w-e-text-container p { margin: 0 0 12px 0 !important; /* 段落间距 */ line-height: 1.8 !important; /* 行高(提升可读性) */ font-size: 14px !important; /* 基础字体大小 */ color: #1f2937 !important; /* 文字颜色 */ } /* 编辑区域聚焦样式 */ .w-e-text-container:focus-within { outline: 2px solid rgba(79, 70, 229, 0.2) !important; /* 聚焦时边框高亮 */ } /* 工具栏分割线样式 */ .w-e-toolbar .w-e-separator { background-color: #e5e7eb !important; /* 分割线颜色 */ margin: 0 6px !important; /* 分割线间距 */ } /* 响应式调整(小屏幕适配) */ @media (max-width: 768px) { .editor-container { border-radius: 4px; /* 小屏幕减小圆角 */ } .w-e-toolbar { padding: 4px 8px !important; /* 小屏幕减小内边距 */ } .w-e-text-container { height: 400px !important; /* 小屏幕减小编辑区高度 */ padding: 12px !important; } } </style>改一改让工具栏悬浮在上面,不会随着页面移动,不论页面滚轮怎么移动都保持在页面上方,右侧添加滚轮使页面可以移动,工具栏上面再搞一个头部,最左边是返回键,中间是AI笔记的标题,最右边是一个头像,点击头像会跳转到个人用户管理界面,头像左边有一个历史记录按钮,点击后会显示一个侧边栏,里面有AI笔记历史,历史记录先留一个按钮就行,头像也先留一个位置就行
最新发布
07-26
<template> <el-container style="height: 100vh; overflow: hidden;"> <!-- 侧边栏 --> <el-aside width="200px" style="background-color: #304156;"> <el-menu default-active="1" class="el-menu-vertical-demo" background-color="#304156" text-color="#bfcbd9" active-text-color="#409EFF"> <el-menu-item index="1"> <i class="el-icon-user"></i> <span>员工管理</span> </el-menu-item> </el-menu> </el-aside> <!-- 主内容区 --> <el-container> <!-- 头部 --> <el-header class="app-header"> <h2 class="app-title">员工管理系统</h2> </el-header> <!-- 主要内容 --> <el-main class="app-content"> <!-- 查询条件 --> <div class="query-section"> <el-row :gutter="20"> <el-col :span="4"> <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable /> </el-col> <el-col :span="4"> <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable> <el-option label="男" :value="0" /> <el-option label="女" :value="1" /> </el-select> </el-col> <el-col :span="4"> <el-select v-model="queryParams.job" placeholder="请选择职位" clearable> <el-option v-for="item in jobOptions" :key="item.value" :label="item.label" :value="item.value" /> </el-select> </el-col> <el-col :span="6"> <el-date-picker v-model="queryParams.dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" /> </el-col> <el-col :span="6" class="action-buttons"> <el-button type="primary" @click="fetchData" icon="el-icon-search">搜索</el-button> <el-button type="success" @click="showAddDialog" icon="el-icon-plus">新增</el-button> <el-button type="danger" @click="batchDelete" icon="el-icon-delete">批量删除</el-button> </el-col> </el-row> </div> <!-- 数据表格 --> <div class="table-section"> <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55" align="center" /> <el-table-column prop="id" label="ID" width="80" align="center" /> <el-table-column prop="name" label="姓名" width="120" /> <el-table-column label="头像" width="100" align="center"> <template #default="scope"> <el-avatar v-if="scope.row.image" :src="scope.row.image" :size="50" shape="square" :preview-src-list="[scope.row.image]" /> <el-avatar v-else :size="50" shape="square"> <i class="el-icon-user-solid" style="font-size: 24px;" /> </el-avatar> </template> </el-table-column> <el-table-column prop="gender" label="性别" width="80" align="center"> <template #default="scope"> <el-tag :type="scope.row.gender === 0 ? 'primary' : 'danger'"> {{ scope.row.gender === 0 ? '男' : '女' }} </el-tag> </template> </el-table-column> <el-table-column prop="job" label="职位" width="150"> <template #default="scope"> <el-tag :type="getJobTagType(scope.row.job)"> {{ jobMap[scope.row.job] || '未知' }} </el-tag> </template> </el-table-column> <el-table-column prop="entrydate" label="入职时间" width="120" align="center" /> <el-table-column prop="createTime" label="创建时间" width="180" align="center" /> <!-- 添加最后修改时间列 --> <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" /> <el-table-column label="操作" width="200" align="center" fixed="right"> <template #default="scope"> <el-button size="small" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button> <el-button size="small" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button> </template> </el-table-column> </el-table> </div> <!-- 分页组件 --> <div class="pagination-section"> <el-pagination background layout="total, prev, pager, next, sizes" :total="total" :page-sizes="[5, 10, 20, 50]" :page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum" @current-change="fetchData" @size-change="handleSizeChange" /> </div> </el-main> </el-container> </el-container> <!-- 新增/编辑对话框 - 优化样式 --> <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :close-on-click-modal="false"> <el-form :model="form" ref="formRef" :rules="formRules" label-width="100px" label-position="left"> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="姓名" prop="name"> <el-input v-model="form.name" /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="用户名" prop="username"> <el-input v-model="form.username" /> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="性别" prop="gender"> <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%"> <el-option label="男" :value="0" /> <el-option label="女" :value="1" /> </el-select> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="职位" prop="job"> <el-select v-model="form.job" placeholder="请选择职位" style="width: 100%"> <el-option v-for="item in jobOptions" :key="item.value" :label="item.label" :value="item.value" /> </el-select> </el-form-item> </el-col> </el-row> <el-row :gutter="20"> <el-col :span="12"> <el-form-item label="密码" prop="password" v-if="!isEdit"> <el-input v-model="form.password" show-password /> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="入职时间" prop="entrydate"> <el-date-picker v-model="form.entrydate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" /> </el-form-item> </el-col> </el-row> <el-form-item label="头像链接" prop="image"> <el-input v-model="form.image" placeholder="请输入图片URL" /> <div class="avatar-preview" v-if="form.image"> <el-image :src="form.image" fit="cover" style="width: 100px; height: 100px; margin-top: 10px;" :preview-src-list="[form.image]" /> </div> </el-form-item> <el-form-item class="form-actions"> <el-button type="primary" @click="submitForm">提交</el-button> <el-button @click="dialogVisible = false">取消</el-button> </el-form-item> </el-form> </el-dialog> </template> <script setup> import { ref, reactive, onMounted } from 'vue'; import axios from 'axios'; import { ElMessage, ElMessageBox } from 'element-plus'; // 设置 axios 实例 const apiClient = axios.create({ baseURL: 'http://localhost:8080/emps', timeout: 5000, }); // 表格数据 const tableData = ref([]); const total = ref(0); const selectedRows = ref([]); const formRef = ref(null); // 查询参数 const queryParams = reactive({ pageNum: 1, pageSize: 5, name: '', gender: null, job: null, dateRange: [] }); // 表单数据 const form = reactive({ id: null, username: '', password: '', name: '', gender: null, job: null, image: '', entrydate: '' }); // 表单验证规则 const formRules = { name: [{ required: true, message: '请输入姓名', trigger: 'blur' }], username: [{ required: true, message: '请输入用户名', trigger: 'blur' }], gender: [{ required: true, message: '请选择性别', trigger: 'change' }], job: [{ required: true, message: '请选择职位', trigger: 'change' }], password: [{ required: true, message: '请输入密码', trigger: 'blur' }], entrydate: [{ required: true, message: '请选择入职日期', trigger: 'change' }] }; // 对话框控制 const dialogVisible = ref(false); const dialogTitle = ref('新增员工'); const isEdit = ref(false); // 职位映射表 const jobMap = { 1: '班主任', 2: '讲师', 3: '学工主管', 4: '教研主管', 5: '咨询师' }; // 职位选项 const jobOptions = [ { label: '班主任', value: 1 }, { label: '讲师', value: 2 }, { label: '学工主管', value: 3 }, { label: '教研主管', value: 4 }, { label: '咨询师', value: 5 } ]; // 获取职位标签类型 const getJobTagType = (job) => { const types = ['', 'success', 'warning', 'danger', 'info', 'primary']; return types[job] || 'info'; }; // 获取数据 const fetchData = async () => { const params = { page: queryParams.pageNum, pageSize: queryParams.pageSize, name: queryParams.name, gender: queryParams.gender, job: queryParams.job, begin: queryParams.dateRange[0] || '', end: queryParams.dateRange[1] || '' }; try { const res = await apiClient.get('', { params }); if (res.data.code === 1) { tableData.value = res.data.data.rows.map(item => ({ ...item, // 格式化最后修改时间 updateTime: formatDateTime(item.updateTime) })); total.value = res.data.data.total; } else { ElMessage.error('获取数据失败:' + res.data.msg); } } catch (error) { console.error('请求出错:', error); ElMessage.error('网络请求失败,请检查后端是否运行正常'); } }; // 时间格式化函数 const formatDateTime = (dateTime) => { if (!dateTime) return ''; // 如果是字符串直接返回 if (typeof dateTime === 'string') { // 尝试解析ISO格式时间 try { const date = new Date(dateTime); return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-'); } catch (e) { return dateTime; } } // 如果是Date对象或时间戳 const date = new Date(dateTime); return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-'); }; // 显示新增对话框 const showAddDialog = () => { dialogTitle.value = '新增员工'; isEdit.value = false; Object.assign(form, { id: null, username: '', password: '', name: '', gender: null, job: null, image: '', entrydate: '' }); dialogVisible.value = true; }; // 显示编辑对话框 const handleEdit = (row) => { dialogTitle.value = '编辑员工'; isEdit.value = true; Object.assign(form, { ...row }); dialogVisible.value = true; }; // 提交表单 const submitForm = async () => { try { await formRef.value.validate(); if (isEdit.value) { await apiClient.put('', form); ElMessage.success('员工信息更新成功'); } else { await apiClient.post('', form); ElMessage.success('员工添加成功'); } dialogVisible.value = false; fetchData(); } catch (error) { if (error.name !== 'Error') { console.error('保存失败:', error); ElMessage.error('操作失败:' + (error.response?.data?.message || error.message)); } } }; // 删除员工 const handleDelete = async (id) => { try { await ElMessageBox.confirm(`确认删除ID为 ${id} 的员工吗?`, '删除确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }); await apiClient.delete(`/${[id]}`); ElMessage.success('删除成功'); fetchData(); } catch (error) { if (error !== 'cancel') { console.error('删除失败:', error); ElMessage.error('删除失败:' + (error.response?.data?.message || error.message)); } } }; // 批量删除 const batchDelete = async () => { if (selectedRows.value.length === 0) { ElMessage.warning('请至少选择一条记录'); return; } try { const ids = selectedRows.value.map(item => item.id); await ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条员工吗?`, '批量删除确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }); await apiClient.delete(`/${ids}`); ElMessage.success(`成功删除 ${ids.length} 条记录`); fetchData(); } catch (error) { if (error !== 'cancel') { console.error('批量删除失败:', error); ElMessage.error('删除失败:' + (error.response?.data?.message || error.message)); } } }; // 表格选择监听 const handleSelectionChange = (rows) => { selectedRows.value = rows; }; // 处理分页大小变化 const handleSizeChange = (size) => { queryParams.pageSize = size; fetchData(); }; // 初始化加载数据 onMounted(() => { fetchData(); }); </script> <style scoped> /* 全局样式 */ .app-header { background-color: #fff; box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08); display: flex; align-items: center; padding: 0 20px; z-index: 1; } .app-title { margin: 0; font-size: 18px; font-weight: 600; color: #333; } .app-content { padding: 20px; background-color: #f0f2f5; height: calc(100vh - 60px); overflow-y: auto; } .query-section { background: #fff; padding: 20px; border-radius: 4px; margin-bottom: 20px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .table-section { background: #fff; padding: 20px; border-radius: 4px; margin-bottom: 20px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .pagination-section { display: flex; justify-content: center; background: #fff; padding: 15px 0; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .action-buttons { display: flex; justify-content: flex-end; } .form-actions { display: flex; justify-content: center; margin-top: 20px; } .avatar-preview { display: flex; justify-content: center; margin-top: 10px; } .el-avatar { background-color: #f5f7fa; display: flex; align-items: center; justify-content: center; } .el-avatar i { color: #909399; } /* 优化对话框样式 */ .el-dialog__body { padding: 20px 25px; } /* 调整操作列按钮间距 */ .el-table .el-button { margin: 0 5px; } /* 确保选择器宽度100% */ .el-select { width: 100%; } </style> 优化一下代码,使代码量更简洁, 重构一下数据表格,使数据表格更美观,现在操作的列后面留了一块空白区域数据表格未能铺满
07-15
<template> <div class="page-container"> <el-row :gutter="20"> <!-- 查询区域 --> <div class="search-wrapper"> <el-form :inline="true" label-width="100px" @submit.prevent="getList"> <el-form-item label="名称"> <el-input v-model="queryParams.name" placeholder="请输入名称" clearable/> </el-form-item> <el-form-item label="责任人"> <el-input v-model="queryParams.respPerson" placeholder="请输入责任人" clearable/> </el-form-item> <el-form-item> <el-button type="primary" @click="getList">查询</el-button> <el-button @click="resetQuery">重置</el-button> <el-button type="primary" @click="toggleGantt" style="margin-left: 10px;" > {{ showGantt ? '收起甘特图' : '展开甘特图' }} </el-button> </el-form-item> </el-form> </div> <div class="table-container"> <el-table ref="table" :data="listData" row-key="uid" border :row-style="{ height: '30px' }" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @row-click="handleRowClick" @expand-change="handleExpandChange" highlight-current-row > <el-table-column prop="code" label="编号" width="120"/> <el-table-column prop="name" label="名称" min-width="180"/> <el-table-column prop="respPerson" label="责任人" width="120"/> <el-table-column prop="schedule" label="完成百分比" width="120"> <template slot-scope="{row}"> <el-progress :percentage="Number(row.schedule)" :show-text="row.schedule > 10" :stroke-width="18" :color="getProgressColor(row.schedule)" /> </template> </el-table-column> <el-table-column prop="planStartDate" label="计划开始日期" width="150"/> <el-table-column prop="planEndDate" label="计划结束日期" width="150"/> <!-- 新增甘特图列 --> <el-table-column label="时间线" min-width="300"> <template slot-scope="{row}"> <div class="gantt-cell" :ref="'gantt_'+row.uid" style="height: 50px;"></div> </template> </el-table-column> <!-- <el-table-column label="操作" width="100">--> <!-- <template slot-scope="scope">--> <!-- <el-button size="mini" icon="el-icon-view" @click.stop="handleUpdate(scope.row)">查看</el-button>--> <!-- </template>--> <!-- </el-table-column>--> </el-table> </div> <!-- <!– 右侧甘特图容器 –>--> <!-- <el-col v-if="showGantt" :span="12">--> <!-- <div ref="ganttContainer" class="gantt-container" style="width: 100%; height: 600px;"></div>--> <!-- </el-col>--> </el-row> <!-- 查看弹窗 --> <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="disable"> <el-row> <el-col :span="12"> <el-form-item label="编号" prop="code"> <el-input v-model="form.code" placeholder="请输入编号"/> </el-form-item> </el-col> <el-col :span="12"> <el-form-item label="名称" prop="name"> <el-input v-model="form.name" placeholder="请输入名称"/> </el-form-item> </el-col> </el-row> <el-row> <el-col :span="24"> <el-form-item label="备注" prop="remarks"> <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" rows="3"/> </el-form-item> </el-col> </el-row> <div class="dialog-footer"> <el-button @click="cancel">取 消</el-button> </div> </el-form> </el-dialog> </div> </template> <script> import gantt from 'dhtmlx-gantt'; import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'; import {getPlan, listPlan} from '@/api/dw/plan/planview'; export default { name: 'Planview', data() { return { expandedKeys: new Set(), // 存储所有展开节点的UID listData: [], total: 0, queryParams: { pageNum: 1, pageSize: 1000, // 树形结构不适合分页,增加单页大小 name: null, respPerson: null }, open: false, title: '', form: {}, rules: { name: [{required: true, message: '名称不能为空', trigger: 'blur'}], schedule: [ {required: true, message: '完成百分比不能为空', trigger: 'blur'}, {type: 'number', message: '输入内容不是有效的数字', trigger: 'blur'} ] }, disable: true, showGantt: true, // 控制甘特图显示 flatData: [], // 扁平化数据 ganttInitialized: false, // 甘特图初始化标志 currentSelectedTask: null, // 当前选中的任务ID ganttExpandState: new Map() // 存储甘特图的展开状态 }; }, mounted() { this.getList(); }, methods: { // 初始化单个任务的甘特图 initTaskGantt(row) { const container = this.$refs[`gantt_${row.uid}`]?.[0]; if (!container || container._ganttInitialized) return; // 创建独立的甘特图实例 const taskGantt = gantt.createGanttInstance(); taskGantt.config.show_chart = false; taskGantt.config.show_grid = false; taskGantt.config.scale_height = 0; taskGantt.config.readonly = true; // 配置时间轴 taskGantt.config.scales = [ {unit: "day", step: 1, format: "%j %D"} ]; // 设置时间范围 const start = new Date(row.planStartDate); const end = new Date(row.planEndDate); taskGantt.setWorkTime({start_date: start, end_date: end}); // 添加任务 taskGantt.parse({ data: [{ id: row.uid, text: row.name, start_date: row.planStartDate, end_date: row.planEndDate, progress: row.schedule / 100, duration: this.calculateDuration(row.planStartDate, row.planEndDate) }] }); // 初始化甘特图 taskGantt.init(container); container._ganttInstance = taskGantt; container._ganttInitialized = true; }, // 计算任务持续时间(天) calculateDuration(start, end) { const startDate = new Date(start); const endDate = new Date(end); return Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)); }, // 获取进度条颜色 getProgressColor(percentage) { // if (percentage < 30) return '#F56C6C'; // if (percentage < 70) return '#E6A23C'; return '#67C23A'; }, // 初始化甘特图 initGantt() { if (!this.$refs.ganttContainer) return; try { // 清除之前的实例(如果存在) if (gantt.$container) { gantt.destructor(); } gantt.config.date_format = '%Y-%m-%d'; gantt.config.scale_unit = 'month'; gantt.config.step = 1; gantt.config.subscales = [ {unit: 'day', step: 1, date: '%j, %D'} ]; gantt.config.columns = [ {name: 'text', label: '任务名称', tree: true, width: 200}, {name: 'start_date', label: '开始时间', align: 'center', width: 100}, {name: 'end_date', label: '结束时间', align: 'center', width: 100}, {name: 'progress', label: '进度', align: 'center', width: 80, template: (task) => `${task.progress * 100}%`} ]; gantt.config.row_height = 30; gantt.config.grid_width = 500; gantt.templates.task_text = (start, end, task) => task.text; gantt.init(this.$refs.ganttContainer); // 绑定事件 gantt.attachEvent('onTaskSelected', (id) => { this.currentSelectedTask = id; this.scrollToTableRow(id); }); // 绑定展开/折叠事件 gantt.attachEvent('onAfterTaskOpen', (id) => { this.ganttExpandState.set(id, true); this.syncGanttExpandToTable(id, true); }); gantt.attachEvent('onAfterTaskClose', (id) => { this.ganttExpandState.set(id, false); this.syncGanttExpandToTable(id, false); }); this.ganttInitialized = true; console.log('甘特图初始化成功'); } catch (e) { console.error('甘特图初始化失败:', e); } }, // 将甘特图的展开状态同步到表格 syncGanttExpandToTable(taskId, expanded) { const row = this.flatData.find(item => item.uid === taskId); if (!row) return; // 更新展开状态 if (expanded) { this.expandedKeys.add(row.uid); } else { this.expandedKeys.delete(row.uid); } // 更新表格UI this.$nextTick(() => { const tableRow = this.$refs.table.$el.querySelector(`[data-id="${row.uid}"]`); if (tableRow) { const expandIcon = tableRow.querySelector('.el-table__expand-icon'); if (expandIcon) { const isExpanded = expandIcon.classList.contains('el-table__expand-icon--expanded'); if (isExpanded !== expanded) { this.$refs.table.toggleRowExpansion(row, expanded); } } } }); }, // 获取数据 async getList() { try { const res = await listPlan(this.queryParams); this.listData = this.handleTree(res.data, 'uid', 'parentUid'); this.$nextTick(() => { // 初始化所有可见行的甘特图 this.initVisibleGantts(); }); } catch (error) { console.error('获取数据失败:', error); } }, // 初始化所有可见行的甘特图 initVisibleGantts() { this.listData.forEach(item => { this.initTaskGantt(item); if (item.children) { item.children.forEach(child => this.initTaskGantt(child)); } }); }, // 更新甘特图数据 updateGantt() { if (!this.ganttInitialized) return; const tasks = this.getVisibleTasks(); console.log('更新甘特图任务数量:', tasks.length); try { // 保存当前甘特图的展开状态 this.saveGanttExpandState(); gantt.clearAll(); gantt.parse({data: tasks, links: []}); // 恢复甘特图的展开状态 this.restoreGanttExpandState(); this.adjustGanttView(tasks); } catch (e) { console.error('更新甘特图失败:', e); } }, // 保存甘特图的展开状态 saveGanttExpandState() { if (!this.flatData.length) return; // 遍历所有任务,保存展开状态 this.flatData.forEach(item => { if (gantt.isTaskExists(item.uid)) { this.ganttExpandState.set(item.uid, gantt.isTaskOpen(item.uid)); } }); }, // 恢复甘特图的展开状态 restoreGanttExpandState() { this.ganttExpandState.forEach((isOpen, taskId) => { if (gantt.isTaskExists(taskId)) { gantt.openTask(taskId, isOpen); } }); }, // 获取当前可见的任务(根据展开状态) getVisibleTasks() { const visibleTasks = []; const collectVisible = (nodes) => { nodes.forEach(node => { visibleTasks.push({ id: node.uid, text: node.name, start_date: node.planStartDate, duration: node.planDuration || 1, progress: (node.schedule || 0) / 100, parent: node.parentUid || 0, open: this.expandedKeys.has(node.uid) // 设置初始展开状态 }); // 如果节点是展开的,递归收集子节点 if (this.expandedKeys.has(node.uid) && node.children) { collectVisible(node.children); } }); }; collectVisible(this.listData); return visibleTasks; }, // 自动调整甘特图视图 adjustGanttView(tasks) { if (!tasks.length) return; // 计算时间范围 const dates = tasks .filter(t => t.start_date) .map(t => new Date(t.start_date)); if (!dates.length) return; const minDate = new Date(Math.min(...dates.map(d => d.getTime()))); const maxDate = new Date(Math.max(...dates.map(t => { const endDate = new Date(t.start_date); endDate.setDate(endDate.getDate() + (t.duration || 0)); return endDate.getTime(); }))); // 设置时间范围 gantt.setWorkTime({ start_date: minDate, end_date: maxDate }); // 根据时间跨度调整缩放级别 const timeDiffInDays = Math.ceil((maxDate - minDate) / (1000 * 60 * 60 * 24)); if (timeDiffInDays <= 7) { gantt.config.scale_unit = 'day'; gantt.config.step = 1; } else if (timeDiffInDays <= 31) { gantt.config.scale_unit = 'week'; gantt.config.step = 1; } else if (timeDiffInDays <= 365) { gantt.config.scale_unit = 'month'; gantt.config.step = 1; } else { gantt.config.scale_unit = 'year'; gantt.config.step = 1; } gantt.render(); }, // 处理树形结构 handleTree(data, idKey = 'uid', parentKey = 'parentUid') { const map = {}; const tree = []; // 创建映射 data.forEach(item => { map[item[idKey]] = {...item, children: []}; }); // 构建树 data.forEach(item => { const parentId = item[parentKey]; if (parentId && map[parentId]) { map[parentId].children.push(map[item[idKey]]); } else { tree.push(map[item[idKey]]); } }); return tree; }, // 行点击事件 handleRowClick(row) { this.$nextTick(() => { // 高亮当前行 this.$refs.table.setCurrentRow(row); // 在甘特图中选中对应任务 if (this.ganttInitialized) { gantt.selectTask(row.uid); gantt.showTask(row.uid); } }); }, // 滚动到表格行 scrollToTableRow(taskId) { const row = this.flatData.find(item => item.uid === taskId); if (!row) return; this.$nextTick(() => { // 确保所有父节点都展开 this.expandParents(row); // 高亮当前行 this.$refs.table.setCurrentRow(row); // 滚动到元素 const tableBody = this.$refs.table.$el.querySelector('.el-table__body-wrapper'); const rowEl = this.$refs.table.$el.querySelector(`[data-id="${row.uid}"]`); if (tableBody && rowEl) { const rowTop = rowEl.offsetTop; const tableHeight = tableBody.clientHeight; tableBody.scrollTop = rowTop - tableHeight / 2; } }); }, // 展开父节点 expandParents(row) { if (!row.parentUid) return; const parent = this.flatData.find(item => item.uid === row.parentUid); if (parent && !this.expandedKeys.has(parent.uid)) { this.expandedKeys.add(parent.uid); this.$refs.table.toggleRowExpansion(parent, true); this.expandParents(parent); } }, // 树展开/折叠更新甘特图 handleExpandChange(row, expanded) { if (expanded && row.children) { this.$nextTick(() => { row.children.forEach(child => this.initTaskGantt(child)); }); } }, // 递归折叠子节点 collapseChildren(node) { if (node.children && node.children.length) { node.children.forEach(child => { this.expandedKeys.delete(child.uid); this.$refs.table.toggleRowExpansion(child, false); this.collapseChildren(child); }); } }, // 切换甘特图显示 - 解决重新初始化问题 toggleGantt() { this.showGantt = !this.showGantt; if (this.showGantt) { this.$nextTick(() => { // 确保每次展开都重新初始化甘特图 this.ganttInitialized = false; this.initGantt(); this.updateGantt(); }); } }, // 获取数据详情 async handleUpdate(row) { try { const res = await getPlan(row.uid); this.form = res.data; this.open = true; this.title = '查看治理计划'; } catch (error) { console.error('获取详情失败:', error); } }, // 取消按钮 cancel() { this.open = false; }, // 重置查询 resetQuery() { this.queryParams = { pageNum: 1, pageSize: 1000, name: null, respPerson: null }; this.getList(); } } }; </script> <style scoped> .page-container { padding: 20px; background-color: #f5f7fa; } .search-wrapper { background-color: #fff; padding: 15px 20px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); margin-bottom: 20px; } .table-container { background-color: #fff; padding: 15px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .gantt-container { background-color: #fff; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); padding: 5px; } .dialog-footer { text-align: right; margin-top: 20px; } .toggle-button { margin-bottom: 15px; } .el-table { width: 100%; } .el-table--border { border: 1px solid #ebeef5; } .el-table__row:hover { background-color: #f5f7fa !important; } .el-progress { margin-top: 8px; } .el-form-item { margin-bottom: 18px; } </style> 优化后的代码,甘特图时间线列没有数据是怎么回事
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值