<style scoped> .wrapper { overflow: hidden; margin: 0px; } </style> <template> <div class="wrapper"> <div ref="threeRef"></div> </div> </template> <script setup lang="ts" type="module"> // 引入three.js import * as THREE from "three"; // 引入扩展库OrbitControls.js import { OrbitControls } from "./build/OrbitControls.js"; import { onMounted, ref } from "vue"; const threeRef = ref();这样配置为何场景不显示
时间: 2025-06-10 18:06:13 浏览: 27
<think>好的,用户之前已经问过如何使用HTML和Three.js显示场景,现在遇到了在Vue组件中配置Three.js但场景不显示的问题。我需要先仔细分析他提供的代码,找出可能的问题点。
首先,用户使用的是Vue 3的setup语法,结合TypeScript。他引入了Three.js和OrbitControls,并且在模板中有一个ref为threeRef的div元素,用来挂载Three的渲染器。
用户提供的代码中,onMounted钩子里初始化了场景、相机、渲染器、立方体和控制器,并调用了animate函数。但场景没有显示出来,可能的原因有几个:
1. **渲染器的domElement没有正确添加到DOM中**:用户创建了WebGLRenderer,但可能没有将renderer.domElement(即canvas元素)添加到threeRef对应的div里。在之前的HTML示例中,他们使用了appendChild,但在Vue中可能需要手动挂载。
2. **样式问题导致容器尺寸为零**:检查.wrapper的CSS,虽然设置了overflow: hidden和margin: 0,但没有设置宽度和高度,可能导致容器没有实际尺寸,渲染器无法正确填充空间。Three.js的渲染器默认可能不会自动适应父容器的大小,需要显式设置尺寸。
3. **相机位置不合适**:相机可能位于物体后面或者太远,导致物体不在视锥体内。在之前的例子中,相机位置被设置为z=5,而用户现在的代码中可能没有调整相机位置,导致看不到物体。
4. **动画循环没有正确启动**:虽然调用了animate函数,但可能因为某些错误导致requestAnimationFrame没有被正确执行,比如在onMounted之外调用,或者有未处理的异常阻止了代码执行。
5. **OrbitControls的配置问题**:OrbitControls可能需要启用enableDamping或设置其他参数,否则相机控制可能有问题,但可能不会导致完全不显示,只是交互问题。
6. **引入路径错误**:用户引入OrbitControls的路径是否正确?例如,"./build/OrbitControls.js"是否存在,如果该模块没有正确导出,可能导致OrbitControls未正确初始化,进而影响渲染。
7. **Vue的响应式引用问题**:threeRef是否正确引用到了DOM元素?在onMounted生命周期中,是否确保DOM已经渲染完成,threeRef.value存在?
接下来需要逐一检查这些可能性。首先,检查渲染器的domElement是否被添加到threeRef对应的div中。用户代码中没有将renderer.domElement添加到threeRef.value,这应该是主要原因。在之前的示例中,他们使用了appendChild,但在Vue中需要使用DOM操作来添加,或者设置渲染器的domElement作为子元素。
其次,检查容器尺寸。.wrapper类虽然设置了overflow:hidden,但没有设置宽度和高度,可能导致父容器的高度为0,进而导致渲染器的canvas没有可见区域。需要给.wrapper或者父容器设置明确的宽度和高度,例如100vh和100vw。
另外,相机的位置是否正确设置?在用户提供的代码中,可能没有调整相机的位置,导致立方体在相机视锥体之外。例如,需要设置camera.position.z = 5,或者在初始化相机后调用camera.lookAt(0,0,0)。
还可能存在其他问题,比如没有处理窗口大小变化的事件,导致在Vue组件中渲染器没有响应式调整尺寸,但这个问题不会导致初次加载不显示,只会导致缩放时显示异常。
总结,最可能的问题是渲染器的canvas没有被添加到DOM中,以及容器尺寸为零导致canvas不可见。需要修改代码,在初始化渲染器后,将domElement添加到threeRef的div中,并确保容器有正确的尺寸。</think>以下是您代码中场景不显示的 **关键原因** 和 **修复方案**:
---
### 问题 1:未挂载 Three.js 画布
**现象**:创建了渲染器但未将画布插入 DOM
**修复**:在初始化渲染器后手动挂载
```ts
// 创建渲染器后添加 ↓
threeRef.value.appendChild(renderer.domElement); // 将canvas插入DOM容器
```
---
### 问题 2:容器尺寸异常
**现象**:`.wrapper` 没有明确尺寸导致画布大小为 0x0
**修复**:为容器设置 CSS 尺寸
```css
.wrapper {
overflow: hidden;
margin: 0;
width: 100vw; /* 全视口宽度 */
height: 100vh; /* 全视口高度 */
}
```
---
### 问题 3:相机位置不当
**现象**:相机与物体重叠或距离过远
**修复**:调整相机位置并设置观察点
```ts
camera.position.set(2, 2, 5); // 设置三维坐标
camera.lookAt(0, 0, 0); // 让相机指向场景中心
```
---
### 完整修正代码
```ts
<script setup lang="ts">
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { onMounted, ref } from "vue";
const threeRef = ref<HTMLElement>();
onMounted(() => {
// 1. 初始化场景
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
// 2. 挂载画布并设置尺寸
renderer.setSize(window.innerWidth, window.innerHeight);
threeRef.value?.appendChild(renderer.domElement); // 关键挂载操作
// 3. 调整相机位置
camera.position.set(2, 2, 5);
camera.lookAt(0, 0, 0);
// 4. 添加立方体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 5. 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // 启用阻尼效果
// 6. 动画循环
function animate() {
requestAnimationFrame(animate);
controls.update(); // 更新控制器
renderer.render(scene, camera);
}
animate();
// 7. 窗口自适应
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
});
</script>
```
---
### 🚀 主要改进点
1. **显式挂载**:通过 `appendChild` 将渲染器画布插入 DOM
2. **容器尺寸**:确保父容器有明确的宽高
3. **相机定位**:使用 `position.set()` + `lookAt()` 精确定位
4. **控制器优化**:启用 `enableDamping` 实现平滑操作
5. **类型安全**:通过 `ref<HTMLElement>` 明确 DOM 元素类型
---
### 补充建议
- 使用 `npm install @types/three` 获取类型定义
- 考虑通过 `three/addons/controls/OrbitControls` 官方路径导入
- 对画布添加 CSS `background: transparent` 实现透明背景
如果仍有问题,可以检查浏览器控制台是否有模块加载错误。
阅读全文
相关推荐










以下頁面代碼如下,當點擊父組件切換按鈕時,子組件的頁面仍能保持原來的頁面狀態,請以完整代碼展示: 父組件代碼(不更改): <template> <button class="external-link" @click="openExternalLink"> 醫仙 </button> <button @click="setCurrentView('mrviewer')" :class="{ active: currentView === 'mrviewer' }"> 醫案閱讀器 </button> <button @click="setCurrentView('mreditor')" :class="{ active: currentView === 'mreditor' }"> 醫案編輯器 </button> <button @click="setCurrentView('dncrud')" :class="{ active: currentView === 'dncrud' }"> 病態編輯器 </button> <keep-alive :include="cachedComponents"> <component :is="currentViewComponent" :key="currentView" /> </keep-alive> </template> <script> import mrviewer from "./components/mrviewer.vue"; import mreditor from "./components/mreditor.vue"; import dncrud from "./components/dncrud.vue"; // 导入病态编辑器组件 export default { components: { mrviewer, mreditor, dncrud }, // 注册组件 data() { return { currentView: "mrviewer", // 需要缓存的组件列表 cachedComponents: ["mrviewer", "mreditor", "dncrud"] }; }, computed: { currentViewComponent() { return this.currentView; } }, methods: { // 设置当前视图并保存状态 setCurrentView(viewName) { // 保存当前组件状态(如果需要) if (this.currentViewComponent && this.currentViewComponent.beforeLeave) { this.currentViewComponent.beforeLeave(); } // 切换到新视图 this.currentView = viewName; // 保存当前视图到本地存储 localStorage.setItem("lastActiveView", viewName); }, openExternalLink() { // 保存当前状态(如果需要) if (this.currentViewComponent && this.currentViewComponent.beforeLeave) { this.currentViewComponent.beforeLeave(); } // 跳转到外部链接 window.location.href = "http://localhost:65358/"; }, // 恢复上次活动视图 restoreLastView() { const lastView = localStorage.getItem("lastActiveView"); if (lastView && this.cachedComponents.includes(lastView)) { this.currentView = lastView; } } }, mounted() { // 组件挂载时恢复上次视图 this.restoreLastView(); } }; </script> <style scoped> .app-container { display: flex; flex-direction: column; min-height: 100vh; } .fixed-menu { position: fixed; top: 0; left: 0; width: 100%; background: #2c3e50; padding: 10px; display: flex; gap: 10px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); z-index: 100; } .fixed-menu button { padding: 8px 16px; border: none; border-radius: 4px; background: #3498db; color: white; cursor: pointer; transition: background 0.3s; } .fixed-menu button:hover { background: #2980b9; } .fixed-menu button.active { background: #e74c3c; font-weight: bold; } .fixed-menu button.external-link { background: #2ecc71; /* 绿色背景区分 */ } .fixed-menu button.external-link:hover { background: #27ae60; } .content-wrapper { flex: 1; margin-top: 60px; /* 增加顶部间距避免内容被顶部菜单遮挡 */ padding: 20px; background: #f5f5f5; height: calc(100vh - 80px); /* 确保内容区域高度适配 */ overflow-y: auto; /* 添加滚动条 */ } </style> 子組件代碼: <template> <button @click="fetchData" class="refresh-btn">刷新數據</button> <input v-model="searchQuery" placeholder="搜索..." class="search-input" /> 每頁顯示: <select v-model.number="pageSize" class="page-size-select"> <option value="1">1筆</option> <option value="4">4筆</option> <option value="10">10筆</option> </select> <button @click="prevPage" :disabled="currentPage === 1">上一页</button> 第 <input type="number" v-model.number="inputPage" min="1" :max="totalPages" class="page-input" @input="handlePageInput"> 頁 / 共 {{ totalPages }} 頁 <button @click="nextPage" :disabled="currentPage === totalPages">下一頁</button> 醫案閱讀器 0"> 醫案 #{{ (currentPage - 1) * pageSize + index + 1 }} {{ key }}: {{ formatDntagValue(value) }} ; 沒有找到匹配的數據 </template> <script> export default { data() { return { api1Data: [], api2Data: [], mergedData: [], currentPage: 1, pageSize: 1, searchQuery: '', sortKey: '', sortOrders: {}, inputPage: 1, // 页码输入框绑定的值 // 字段名称映射表 fieldNames: { 'mrcase': '醫案全文', 'mrname': '醫案命名', 'mrposter': '醫案提交者', 'mrlasttime': '最後編輯時間', 'mreditnumber': '編輯次數', 'mrreadnumber': '閱讀次數', 'mrpriority': '重要性', 'dntag': '病態名稱' }, inputTimeout: null, // 用于输入防抖 dnNames: [] // 存储所有病态名称 }; }, computed: { filteredData() { const query = this.searchQuery.trim(); // 判斷是否為數字(即搜尋 ID) if (query && /^\d+$/.test(query)) { const idToSearch = parseInt(query, 10); return this.mergedData.filter(item => item.id === idToSearch); } // 一般搜索邏輯 if (!query) return this.mergedData; const lowerQuery = query.toLowerCase(); return this.mergedData.filter(item => { return Object.values(item).some(value => { if (value === null || value === undefined) return false; // 处理数组类型的值 if (Array.isArray(value)) { return value.some(subValue => { if (typeof subValue === 'object' && subValue !== null) { return JSON.stringify(subValue).toLowerCase().includes(lowerQuery); } return String(subValue).toLowerCase().includes(lowerQuery); }); } // 处理对象类型的值 if (typeof value === 'object' && value !== null) { return JSON.stringify(value).toLowerCase().includes(lowerQuery); } return String(value).toLowerCase().includes(lowerQuery); }); }); }, sortedData() { if (!this.sortKey) return this.filteredData; const order = this.sortOrders[this.sortKey] || 1; return [...this.filteredData].sort((a, b) => { const getValue = (obj) => { const val = obj[this.sortKey]; if (Array.isArray(val)) { return JSON.stringify(val); } return val; }; const aValue = getValue(a); const bValue = getValue(b); if (aValue === bValue) return 0; return aValue > bValue ? order : -order; }); }, paginatedData() { const start = (this.currentPage - 1) * Number(this.pageSize); const end = start + Number(this.pageSize); return this.sortedData.slice(start, end); }, totalPages() { return Math.ceil(this.filteredData.length / this.pageSize) || 1; } }, watch: { // 监控分页大小变化 pageSize() { // 重置到第一页 this.currentPage = 1; this.inputPage = 1; // 同步输入框的值 }, // 监控当前页码变化 currentPage(newVal) { // 同步输入框的值 this.inputPage = newVal; }, // 监控过滤数据变化 filteredData() { // 确保当前页码有效 if (this.currentPage > this.totalPages) { this.currentPage = Math.max(1, this.totalPages); } // 同步输入框的值 this.inputPage = this.currentPage; } }, methods: { async fetchData() { try { const api1Response = await fetch("MRInfo/?format=json"); this.api1Data = await api1Response.json(); const api2Response = await fetch("DNTag/?format=json"); this.api2Data = await api2Response.json(); // 提取所有dnname this.dnNames = this.api2Data.map(item => item.dnname).filter(name => name && name.trim()); // 按长度降序排序(确保长字符串优先匹配) this.dnNames.sort((a, b) => b.length - a.length); this.mergeData(); this.currentPage = 1; this.inputPage = 1; // 重置输入框 } catch (error) { console.error("獲取數據失敗:", error); alert("數據加載失敗,請稍後重試"); } }, mergeData() { this.mergedData = this.api1Data.map((item) => { const newItem = { ...item }; if (newItem.dntag && Array.isArray(newItem.dntag)) { newItem.dntag = newItem.dntag.map((tagId) => { const matchedItem = this.api2Data.find( (api2Item) => api2Item.id === tagId ); return matchedItem || { id: tagId, dnname: "未找到匹配的數據" }; }); } return newItem; }); this.sortOrders = {}; if (this.mergedData.length > 0) { Object.keys(this.mergedData[0]).forEach(key => { this.sortOrders[key] = 1; }); } }, // 处理字段名称映射 processFieldNames(item) { const result = {}; for (const key in item) { // 使用映射表转换字段名,如果没有映射则使用原字段名 const newKey = this.fieldNames[key] || key; result[newKey] = item[key]; } return result; }, // 高亮匹配文本的方法 highlightMatches(text) { if (!text || typeof text !== 'string' || this.dnNames.length === 0) { return text; } // 创建正则表达式(转义特殊字符) const pattern = new RegExp( this.dnNames .map(name => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) .join('|'), 'gi' ); // 替换匹配文本 return text.replace(pattern, match => ${match} ); }, formatValue(value, fieldName) { if (value === null || value === undefined) return ''; // 医案全文字段特殊处理 if (fieldName === '醫案全文' && typeof value === 'string') { return this.highlightMatches(value); } // 其他字段保持原逻辑 if (typeof value === 'string' && value.startsWith('http')) { return ${value}; } return value; }, // 专门处理dntag字段的显示格式 formatDntagValue(dntagArray) { return dntagArray.map(tagObj => { // 只显示name属性,隐藏id等其他属性 return tagObj.dnname || tagObj.name || '未命名標籤'; }).join(';'); // 使用大写分号分隔 }, sortBy(key) { // 需要从中文名称映射回原始字段名进行排序 const originalKey = Object.keys(this.fieldNames).find( origKey => this.fieldNames[origKey] === key ) || key; this.sortKey = originalKey; this.sortOrders[originalKey] = this.sortOrders[originalKey] * -1; }, prevPage() { if (this.currentPage > 1) { this.currentPage--; } }, nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; } }, // 实时处理页码输入 handlePageInput() { // 清除之前的定时器 clearTimeout(this.inputTimeout); // 设置新的定时器(防抖处理) this.inputTimeout = setTimeout(() => { this.goToPage(); }, 300); // 300毫秒后执行 }, // 跳转到指定页码 goToPage() { // 处理空值情况 if (this.inputPage === null || this.inputPage === undefined || this.inputPage === '') { this.inputPage = this.currentPage; return; } // 转换为整数 const page = parseInt(this.inputPage); // 处理非数字情况 if (isNaN(page)) { this.inputPage = this.currentPage; return; } // 确保页码在有效范围内 if (page < 1) { this.currentPage = 1; } else if (page > this.totalPages) { this.currentPage = this.totalPages; } else { this.currentPage = page; } // 同步输入框显示 this.inputPage = this.currentPage; } }, mounted() { this.fetchData(); } }; </script> <style scoped> .container { max-width: 1200px; margin: 0px; padding: 0px; } .control-panel { margin-bottom: 0px; display: flex; flex-wrap: wrap; gap: 10px; justify-content: flex-end; align-items: center; position: fixed; bottom: 0; left: 0; width: 100%; background-color: #ffd800ff; z-index: 999; padding: 10px 20px; box-sizing: border-box; } .content-area { position: fixed; top: 56px; bottom: 45px; /* 位于底部按钮上方 */ left: 0; width: 100%; background: white; padding: 1px; z-index: 100; overflow-y: auto; } .refresh-btn { padding: 4px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } .refresh-btn:hover { background-color: #45a049; } .search-input { padding: 8px; border: 1px solid #ddd; border-radius: 4px; flex-grow: 1; max-width: 300px; } .pagination-controls { display: flex; align-items: center; gap: 5px; } .page-size-select { padding: 4px; border-radius: 4px; width: 70px; } /* 页码输入框样式 */ .page-input { width: 50px; padding: 4px; border: 1px solid #ddd; border-radius: 4px; text-align: center; } /* 水平记录样式 */ .horizontal-records { display: flex; flex-direction: column; gap: 20px; } .record-card { border: 1px solid #ddd; border-radius: 4px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .record-header { padding: 12px 16px; background-color: #f5f5f5; border-bottom: 1px solid #ddd; } .record-header h3 { margin: 0; font-size: 1.1em; } .record-body { padding: 16px; } .record-field { display: flex; margin-bottom: 12px; line-height: 1.5; } .record-field:last-child { margin-bottom: 0; } .field-name { font-weight: bold; min-width: 120px; color: #555; } .field-value { flex-grow: 1; display: flex; flex-wrap: wrap; gap: 8px; } .dntag-value { display: flex; flex-wrap: wrap; gap: 8px; } .array-value { display: flex; flex-wrap: wrap; gap: 8px; } .no-data { padding: 20px; text-align: center; color: #666; font-style: italic; } button:disabled { opacity: 0.5; cursor: not-allowed; } </style>





<template> <a-card :bordered="false" :class="{isShowStyle: indirectFlag}"> <a-form layout="inline" @keyup.enter.native="searchQuery"> <a-row :gutter='24'> <a-col :span='8'> <a-form-item label='主机厂'> <a-input v-model.trim='queryParam.oems' placeholder='请输入主机厂名称'></a-input> </a-form-item> </a-col> <a-col :span='8'> <a-form-item label='客户名称'> <a-input v-model.trim='queryParam.endUser' placeholder='请输入客户名称'></a-input> </a-form-item> </a-col> <a-col :span='8'> <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button> <a-button type='primary' @click='reset' icon='reload' style='margin-left: 8px'>重置</a-button> </a-col> </a-row> </a-form> <a-upload v-if="!hiddenFlag" name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel"> <a-button type="primary" icon="import" :disabled="hiddenFlag">导入</a-button> </a-upload> <a-button icon='link' type='primary' @click='outmb1' :disabled="hiddenFlag"> 导入模板 </a-button> <a-button type="primary" @click="bacthSave" v-if="indirectModal" :disabled="hiddenFlag">保存</a-button> <a-button type="primary" @click="subStatus" v-if="indirectModal" :disabled="hiddenFlag">提交</a-button> <a-dropdown v-if='selectedRowKeys.length > 0'> <a-menu slot='overlay'> <a-menu-item key='1' @click='batchDelete'> <a-icon type='delete' /> 删除 </a-menu-item> </a-menu> <a-button style='margin-left: 8px'> 批量操作 <a-icon type='down' /> </a-button> </a-dropdown> <j-editable-table v-if="indirectModal" ref="editableTable" size="middle" bordered rowKey="id" :columns="dynamicColumns" :dataSource="dataSource" :rowNumber="true" :pagination="ipagination" :loading="loading" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" class="j-table-force-nowrap" :actionButton="true" :disabledRows="{ status:1}" @change="handleTableChange"> <template v-slot:oemsSlot="props"> <a-input v-model='props.text' placeholder='请输入主机厂' :disabled="isDisabled(props)" @input="oemsInput(props)"> <a-icon slot='prefix' type='cluster' @click.stop='handleOemsClick(props)'/> </a-input> </template> <template v-slot:productSearchSlot="props"> <a-select v-model="props.text" show-search placeholder="请选择产品名称" :default-active-first-option="false" :show-arrow="false" :filter-option="false" :not-found-content="null" style="width: 100%" @search="handleProductSearch" @change="handleProductChange(props)" > <a-select-option v-for="item in productList" :key="item.value" :value="item.value"> {{ item.text }} </a-select-option> </a-select> </template> <template v-slot:productSlot="props"> <j-search-select-tag v-model="props.text" placeholder="请选择产品名称" dict="bs_inventory GROUP BY cInvName, cInvName, cInvName" /> </template> <template v-slot:publishSlot="props"> <a-input-search v-model="props.text" placeholder="请先选择用户" readOnly unselectable="on" @search="onSearchDepUser(props)"> <a-button slot="enterButton" :disabled="false">选择用户</a-button> </a-input-search> <j-select-user-by-dep-modal ref="selectModal" modal-width="80%" :multi="false" @ok="selectOK" :user-ids="props.value" @initComp="initComp"/> </template> <j-ellipsis :value='text' :length='40'/> </j-editable-table> <a-table v-else ref="table" size="middle" bordered rowKey="id" :columns="columns" :dataSource="dataSource" :pagination="ipagination" :loading="loading" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" class="j-table-force-nowrap" @change="handleTableChange"> <j-ellipsis :value='text' :length='40'/> 编辑 <a-divider type="vertical"/> <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)"> 删除 </a-popconfirm> </a-table> <indirectBusinessProducts-modal ref="modalForm" :indirectModal="indirectModal" @ok="modalFormOk"></indirectBusinessProducts-modal> <indirectBusinessProducts-item-modal ref="modalItemForm" @ok="modalFormOk"></indirectBusinessProducts-item-modal> <a-modal title='客户名称(主机厂)' :width='1000' :visible='cusVisible' @ok='handleCusSubmit' @cancel='closeCusModal' cancelText='关闭'> <cus-component ref='cusComponent'></cus-component> </a-modal> </a-card> </template> <script> import '@/assets/less/TableExpand.less' import {mixinDevice} from '@/utils/mixin' import {JeecgListMixin} from '@/mixins/JeecgListMixin' import IndirectBusinessProductsModal from './modules/IndirectBusinessProductsModal' import JEllipsis from "../../../components/jeecg/JEllipsis.vue"; import IndirectBusinessProductsItemModal from "./modules/IndirectBusinessProductsItemModal.vue"; import {deleteAction, downFile, getAction, postAction, putAction} from "../../../api/manage"; import {filterDictText, initDictOptions} from '@/components/dict/JDictSelectUtil' import {FormTypes} from '@/utils/JEditableTableUtil' import JEditableTable from "@comp/jeecg/JEditableTable.vue"; import CusComponent from "@views/modules/eoa/plan/components/CusComponent.vue"; import JSelectUserByDep from "@comp/jeecgbiz/JSelectUserByDep.vue"; import JSelectUserByDepModal from "@comp/jeecgbiz/modal/JSelectUserByDepModal.vue"; import JSearchSelectTag from "@comp/dict/JSearchSelectTag.vue"; export default { name: "IndirectBusinessProductsList", mixins: [JeecgListMixin, mixinDevice], components: { JSearchSelectTag, JSelectUserByDepModal, JSelectUserByDep, CusComponent, JEditableTable, IndirectBusinessProductsItemModal, JEllipsis, IndirectBusinessProductsModal }, props: { indirectFlag: { type: Boolean, default: false }, indirectModal: { type: Object, default: () => { } }, hiddenFlag: { type: Boolean, default: false }, }, data() { return { usernames: null, value: null, userIds: null, description: 'indirect_business_products管理页面', statusDictOptions: [], busType: 'my', cusVisible: false, // 表头 columns: [ { title: '#', dataIndex: '', key: 'rowIndex', width: 60, align: "center", customRender: function (t, r, index) { return parseInt(index) + 1; } }, // { // title: '客户名称(主机厂)', // align: "center", // dataIndex: 'oems' // }, { title: '客户名称', align: "center", dataIndex: 'endUser' }, { title: '终端用户', align: "center", dataIndex: 'oems', scopedSlots: {customRender: 'titleSlot'}, width: 100 }, { title: '车型(米)', align: "center", dataIndex: 'carType', customRender: (text, record, index) => { //字典值替换通用方法 return filterDictText(this.vehicleModelOptions, text); } }, { title: '产品明细', align: "center", scopedSlots: {customRender: 'titleSlot'}, dataIndex: 'productDetails' }, { title: '发布数量', align: "center", dataIndex: 'number' }, { title: '预测金额', align: "center", dataIndex: 'redictedAmount' }, { title: '发布人', align: "center", dataIndex: 'publishName' }, { title: '发布时间', align: "center", dataIndex: 'publishTime', customRender: function (text) { return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text) } }, { title: '产品类型', align: "center", dataIndex: 'productType', customRender: (text, record, index) => { //字典值替换通用方法 return filterDictText(this.productTypeOptions, text); } }, // { // title: '产品大类', // align: "center", // dataIndex: 'productCategories' // }, { title: '提交状态', align: "center", dataIndex: 'status', customRender: (text, record, index) => { //字典值替换通用方法 return filterDictText(this.statusDictOptions, text); } }, { title: '操作', dataIndex: 'action', align: "center", // fixed:"right", width: 147, scopedSlots: {customRender: 'action'} } ], url: { list: "/indirect_business/products/list", delete: "/indirect_business/products/delete", deleteBatch: "/indirect_business/products/deleteBatch", setStatus: "/indirect_business/products/setStatus", batchAdd: "/indirect_business/products/batchAdd", teamExcelTemplate: "indirect_business/indirectBusiness/teamExcelTemplate", teamExcelTemplateProduct: "indirect_business/indirectBusiness/teamExcelTemplateProduct", importExcelUrl: "indirect_business/products/importExcel", }, dictOptions: {}, queryParam:{ status:'1' }, productList: [],//储存产品信息列表 currentClickRowId: null, // 存储当前点击的行ID } }, computed: { importExcelUrl: function () { if (!this.indirectModal) { return ${window._CONFIG['domianURL']}/${this.url.importExcelUrl}; } else { return ${window._CONFIG['domianURL']}/${this.url.importExcelUrl}?busId=${this.indirectModal.busId}&endUser=${this.indirectModal.endCustomer}; } }, getLoginUsername() { return this.$store.getters.userInfo.username; }, loginPermissions() { return this.indirectModal.helpPerson.includes(this.$store.getters.userInfo.username); }, rowSelection() { return { onChange: (selectedRowKeys, selectedRows) => { this.onSelectChange(selectedRowKeys, selectedRows); }, getCheckboxProps: record => ({ props: { disabled: record.status === 1 || record.status === null }, }), }; }, dynamicColumns() { const baseColumns = [ { title: "busId", align: "center", key: "busId", type: FormTypes.hidden, defaultValue: this.indirectModal.busId }, // 动态客户名称列 { title: this.indirectModal.category === '1' ? '客户名称' : '终端客户名称', align: "center", key: 'endUser', type: FormTypes.input, placeholder: '请输入客户名称', disabled: true, defaultValue: this.indirectModal.endCustomer, width: '220px' } ]; if (this.indirectModal.category === '2'){ baseColumns.push({ title: '主机厂', align: "center", key: 'oems', placeholder: "请选择主机厂", type: FormTypes.slot, slotName: 'oemsSlot', validateRules: this.indirectModal.category === '2' ? [ { required: true, message: '主机厂不能为空' }, { validator: (rule, value, callback) => { if (value === '' || value === null || value === undefined) { callback(new Error('请选择主机厂')); // 配合 required 使用 } } } ] : [], width: '220px', }); } baseColumns.push({ title: '车型(米)', align: "center", key: 'carType', type: FormTypes.select, dictCode: 'vehicle_model', placeholder: '请选择车型', customRender: (text, record, index) => { //字典值替换通用方法 return filterDictText(this.vehicleModelOptions, text); }, width: '150px' }) baseColumns.push({ title: '产品名称', align: "center", key: 'productDetails', placeholder: "请选择产品名称", type: FormTypes.slot, slotName: 'productSearchSlot', width: '240px' }) baseColumns.push({ title: '发布数量', align: "center", key: 'number', type: FormTypes.input, inputType: 'number', placeholder: "请输入发布数量", validateRules: [ { pattern: /^[1-9]\d*$/, // 正整数正则 message: '发布数量必须是正整数' } ], width: '150px' }) baseColumns.push({ title: '预测金额', align: "center", key: 'redictedAmount', type: FormTypes.input, inputType: 'number', placeholder: "请输入预测金额", // 动态校验规则(category == '2' 时必填且必须为正数) validateRules: this.indirectModal.category === '2' ? [ { required: true, message: '预测金额不能为空', trigger: ['blur', 'change'] // 触发校验的时机 }, { pattern: /^(0|[1-9]\d*)(\.\d+)?$/, // 正整数正则 message: '发布数量必须是正数' } ] : [], width: '150px' }) if (this.indirectModal.category === '2'){ baseColumns.push({ title: '主机厂负责人', align: "center", key: 'oemResponsiblePerson', type: FormTypes.hidden, }); } // if (this.indirectModal.category === '2'){ // baseColumns.push({ // title: '主机厂负责人', // align: "center", // key: 'oemResponsiblePersonName', // type: FormTypes.input, // disabled: true, // width: '200px' // }); // } baseColumns.push({ title: '发布人', align: "center", key: 'publishBy', type: FormTypes.hidden, defaultValue: this.$store.getters.userInfo.username, placeholder: "请选择发布人", width: '240px' }) baseColumns.push({ title: '发布人', align: "center", key: 'publishName', type: FormTypes.slot, slotName: 'publishSlot', defaultValue: this.$store.getters.userInfo.realname, placeholder: "请选择发布人", width: '240px' }) baseColumns.push({ title: '发布时间', align: "center", key: 'publishTime', type: FormTypes.date, customRender: function (text) { return !text ? "" : (text.length > 10 ? text.substr(0, 10) : text) }, defaultValue: this.formatDate(new Date()), width: '170px' }) baseColumns.push({ title: '产品类型', align: "center", key: 'productType', placeholder: "请选择产品类型", type: FormTypes.select, dictCode: 'product_type', customRender: (text, record, index) => { //字典值替换通用方法 return filterDictText(this.productTypeOptions, text); }, defaultValue: '0', width: '130px' }) baseColumns.push({ title: '提交状态', align: "center", key: 'status', type: FormTypes.select, dictCode: 'public_status', customRender: (text, record, index) => { //字典值替换通用方法 return filterDictText(this.statusDictOptions, text); }, defaultValue: '0', disabled: true, width: '130px' }) return baseColumns; }, }, methods: { initDictConfig() { getAction('/base/bsInventory/distinctAllList',null).then((res) => { if (res.success) { this.productList = res.result.map(item => ({ text: item.cinvname, value: item.cinvname })) } }) //判断查询条件 if (!this.indirectModal){ this.queryParam.status = 1 this.loadData(1) }else{ this.queryParam.busId = this.indirectModal.busId this.queryParam.status = '' this.loadData(1) } console.log('this.queryParam.status',this.queryParam.status) initDictOptions('public_status').then((res) => { if (res.success) { this.statusDictOptions = res.result } }) initDictOptions('vehicle_model').then((res) => { if (res.success) { this.vehicleModelOptions = res.result } }) initDictOptions('product_type').then((res) => { if (res.success) { this.productTypeOptions = res.result } }) }, // 产品名称远程搜索 handleProductSearch(value) { if (!value) return; // 空输入不查询 // 调用接口查询匹配的产品 getAction('/base/bsInventory/distinctAllList', { 'cinvname': value }).then(res => { if (res.success) { this.productList = res.result.map(item => ({ text: item.cinvname, value: item.cinvname })); } }); }, handleProductChange(props) { // 存储当前点击的行记录和ID this.currentClickRowId = props.rowId; this.$refs.editableTable.setValues([{ rowKey: this.currentClickRowId, values: { 'productDetails': props.text } }]); }, outmb() { downFile(this.url.teamExcelTemplate, '').then((res) => { if (!res) { this.$message.warning('文件下载失败') return } let blob = new Blob([res], {type: 'application/vnd.ms-excel'}) let downloadElement = document.createElement('a') let href = window.URL.createObjectURL(blob) // 创建下载的链接 downloadElement.href = href downloadElement.download = '间接销售登记表导入模板.xls' // 下载后文件名 document.body.appendChild(downloadElement) downloadElement.click() // 点击下载 document.body.removeChild(downloadElement) // 下载完成移除元素 window.URL.revokeObjectURL(href) // 释放掉blob对象 }) }, outmb1() { downFile(this.url.teamExcelTemplateProduct, '').then((res) => { if (!res) { this.$message.warning('文件下载失败') return } let blob = new Blob([res], {type: 'application/vnd.ms-excel'}) let downloadElement = document.createElement('a') let href = window.URL.createObjectURL(blob) // 创建下载的链接 downloadElement.href = href downloadElement.download = '间接销售登记导入模板.xlsx' // 下载后文件名 document.body.appendChild(downloadElement) downloadElement.click() // 点击下载 document.body.removeChild(downloadElement) // 下载完成移除元素 window.URL.revokeObjectURL(href) // 释放掉blob对象 }) }, subStatus(){ const ids = this.$refs.editableTable.getSelection() if (ids.length==0){ this.$message.warn("请选择一条记录") return; } const selectedRow = this.$refs.editableTable.getValuesSync({rowIds: ids}).values selectedRow.forEach(item => { if (item.status == "1"){ this.$message.warn("请选择未提交的数据") return; } }) let that = this that.$confirm({ title: '提示', content: '确认提交吗?', onOk: function() { putAction(that.url.setStatus, selectedRow).then((res) => { if (res.success) { that.$message.success(res.message); that.loadData(); that.onClearSelected(); } else { that.$message.warning(res.message); that.loadData(); } }) } }) }, bacthSave() { this.$refs.editableTable.getValues(error => { if (error === 0) { let that = this postAction(that.url.batchAdd, this.$refs.editableTable.getValuesSync().values).then((res) => { if (res.success) { that.$message.success(res.message); that.loadData(); } else { that.$message.warning(res.message); that.loadData(); } }) } else { this.$message.error('验证未通过') } }) }, reset(){ this.queryParam = {status:'1'} this.loadData() }, batchDelete: function () { if(!this.url.deleteBatch){ this.$message.error("请设置url.deleteBatch属性!") return } if (this.selectedRowKeys.length <= 0) { this.$message.warning('请选择一条记录!'); return; } else if (this.selectionRows.some(item => item.status != 0)) { this.$message.warning('请选择未提交记录!') return; } else { var ids = ""; for (var a = 0; a < this.selectedRowKeys.length; a++) { ids += this.selectedRowKeys[a] + ","; } var that = this; this.$confirm({ title: "确认删除", content: "是否删除选中数据?", onOk: function () { that.loading = true; deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => { if (res.success) { that.$message.success(res.message); that.loadData(); that.onClearSelected(); } else { that.$message.warning(res.message); } }).finally(() => { that.loading = false; }); } }); } }, handleCusSubmit() { if (!this.$refs.cusComponent.selectionRows || this.$refs.cusComponent.selectionRows.length === 0) { this.$message.warning('请选择一条记录') return false } var customerNames = ""; var oemResponsiblePerson = ""; var oemResponsiblePersonName = ""; for (var a = 0; a < this.$refs.cusComponent.selectedRowRecords.length; a++) { customerNames += this.$refs.cusComponent.selectedRowRecords[a].customerName + ","; if (this.$refs.cusComponent.selectedRowRecords[a].responsiblePerson !== null) { oemResponsiblePerson += this.$refs.cusComponent.selectedRowRecords[a].responsiblePerson + ","; } if (this.$refs.cusComponent.selectedRowRecords[a].responsiblePersonName!==null){ oemResponsiblePersonName += this.$refs.cusComponent.selectedRowRecords[a].responsiblePersonName + ","; } } const oems = customerNames.substr(0,customerNames.length-1) const oemResponsiblePersons = oemResponsiblePerson.substr(0,oemResponsiblePerson.length-1) const oemResponsiblePersonNames = oemResponsiblePersonName.substr(0,oemResponsiblePersonName.length-1) // 找到当前点击的行并更新数据 this.$refs.editableTable.setValues( [{ rowKey: this.currentClickRowId, values: { 'oems': oems, 'oemResponsiblePerson': oemResponsiblePersons, 'oemResponsiblePersonName': oemResponsiblePersonNames, } }] ) this.closeCusModal() }, oemsInput(props) { // 存储当前点击的行记录和ID this.currentClickRowId = props.rowId; // 找到当前点击的行并更新数据 this.$refs.editableTable.setValues( [{ rowKey: this.currentClickRowId, values: { 'oems': props.text } }] ) }, handleOemsClick(props) { console.log("主机厂",this.$refs.editableTable.getValues({rowIds: props.rowId})) // 存储当前点击的行记录和ID this.currentClickRowId = props.rowId; this.openCusModal(); // 直接打开弹窗 }, openCusModal() { this.cusVisible = true }, closeCusModal() { this.$refs.cusComponent.selectionRows = [] this.$refs.cusComponent.selectedRowKeys = [] this.$refs.cusComponent.queryParam = {} this.cusVisible = false }, formatDate(date) { const year = date.getFullYear() const month = (date.getMonth() + 1).toString().padStart(2, '0') const day = date.getDate().toString().padStart(2, '0') return ${year}-${month}-${day} }, initComp(userNames) { this.userNames = userNames }, onSearchDepUser(props) { this.currentClickRowId = props.rowId if (this.isSelectUser) this.$refs.selectModal.queryParam.username = this.value; this.$refs.selectModal.showModal() this.$refs.selectModal.queryParam.username = ""; }, selectOK(rows, idstr) { if (!rows) { this.userNames = '' this.userIds = '' } else { let temp = '' for (let item of rows) { temp += ',' + item.realname } this.userNames = temp.substring(1) this.userIds = idstr // 找到当前点击的行并更新数据 this.$refs.editableTable.setValues( [{ rowKey: this.currentClickRowId, values: { 'publishBy': this.userIds, 'publishName': this.userNames, } }] ) } }, // 判断是否禁用 isDisabled(props){ const item = this.$refs.editableTable.getValuesSync({rowIds: [props.rowId]}) return item.values[0].status === '1' } } } </script> <style scoped> @import '~@assets/less/common.less'; .isShowStyle /deep/ .ant-card-body { padding: unset; } </style>中<template v-slot:oemsSlot="props"> <a-input v-model='props.text' placeholder='请输入主机厂' :disabled="isDisabled(props)" @input="oemsInput(props)"> <a-icon slot='prefix' type='cluster' @click.stop='handleOemsClick(props)'/> </a-input> </template>插槽的:disabled我这样子用会报错,应该怎么使用,jeecg



