重庆家居网站制作公司/百度手机助手下载安卓版
1.关于vue2 antd 视图更新问题
1.一种强制更新
Vue2是通过用Object…defineProperty来设置数据的getter和setter实现对数据和以及视图改变的监听的。对于数组和对象这种引用类型来说,getter和setter无法检测到它们内部的变化。用这种
this.$set(this.form, "fileUrl", urlArr.join(","));
2.如果碰到
a-form :form="form"
form: this.$form.createForm(this),
<a-form :form="form" @submit="handleSubmit"><a-form-item:labelCol="labelCol":wrapperCol="wrapperCol"label="上级仓库"hasFeedback><a-tree-select:treeData="dataSource"placeholder="请选择":replaceFields="{title: 'name',key: 'id',value: 'id',children: 'children',}"v-decorator="['parentId', { initialValue: formData.parentId }]"/></a-form-item><a-form-item:labelCol="labelCol":wrapperCol="wrapperCol"label="仓库名称"hasFeedback><a-inputplaceholder="仓库名称"v-decorator="['name',{initialValue: formData.name,rules: validatorRules.inputIf.rules,},]"/></a-form-item><a-form-item:labelCol="labelCol":wrapperCol="wrapperCol"label="所属机构"required><vorganTreev-decorator="['orgId',{initialValue: formData.orgId,rules: validatorRules.inputIf.rules,},]"></vorganTree></a-form-item><a-form-item:labelCol="labelCol":wrapperCol="wrapperCol2"label="位置地点"><div class="disflex"><a-inputv-decorator="['address',{initialValue: formData.address,rules: validatorRules.inputIf.rules,},]"/><a-icon type="environment" @click="mapShow(true)" class="mapico" /><a-button type="link" @click="mapShow(true)">选择地点</a-button></div></a-form-item></a-form>
a-form :form="form"
form: this.$form.createForm(this),
那么使用
this.form.setFieldsValue({ address: val.address })来更新表单的值,以触发视图的更新。
清空的话
this.form.resetFields();
3.通常双向绑定如果不行试试前两种。
2.关于封装好了表格 使用
1.导入
import STable from "@/components/table/";
index.js
import T from "ant-design-vue/es/table/Table";
import get from "lodash.get"
export default {data() {return {needTotalList: [],selectedRows: [],selectedRowKeys: [],localLoading: false,localDataSource: [],localPagination: Object.assign({}, T.props.pagination)};},props: Object.assign({}, T.props, {rowKey: {type: [String, Function],default: 'id'},data: {type: Function,required: true},pageNum: {type: Number,default: 1},pageSize: {type: Number,default: 10},showSizeChanger: {type: Boolean,default: true},showAlertInfo: {type: Boolean,default: false},showPagination: {default: 'auto'},deleteShow: { // 删除键type: Boolean,default: false},bordered: {type: Boolean,default: true},}),watch: {'localPagination.current'(val) {this.$router.push({name: this.$route.name,params: Object.assign({}, this.$route.params, {current: val}),});},pageNum(val) {Object.assign(this.localPagination, {current: val});},pageSize(val) {Object.assign(this.localPagination, {pageSize: val});},showSizeChanger(val) {Object.assign(this.localPagination, {showSizeChanger: val});}},zzh() {const that = thisreturn that;},created() {this.localPagination = ['auto', true].includes(this.showPagination) && Object.assign({}, this.localPagination, {current: this.pageNum,pageSize: this.pageSize,showSizeChanger: this.showSizeChanger});this.needTotalList = this.initTotalList(this.columns)this.loadData();},methods: {loadingShow(value) {this.localLoading = value},refresh() {var mm = {current: 1,total: 0,size: this.pageSize,}this.loadData(mm);},deleteRefresh() {this.loadData()},loadData(pagination, filters, sorter) {this.localLoading = truevar result = this.data(Object.assign({current: (pagination && pagination.current) ||this.localPagination.current,size: (pagination && pagination.pageSize) ||this.localPagination.pageSize},(sorter && sorter.field && {sortField: sorter.field}) || {},(sorter && sorter.order && {sortOrder: sorter.order}) || {}, {...filters}));if (result instanceof Promise) {result.then(r => {this.localPagination = Object.assign({}, this.localPagination, {current: (pagination && pagination.current) ||this.localPagination.current, // 返回结果中的当前分页数total: r.totalCount, // 返回结果中的总记录数showSizeChanger: this.showSizeChanger,pageSize: (pagination && pagination.pageSize) ||this.localPagination.pageSize});!r.totalCount && ['auto', false].includes(this.showPagination) && (this.localPagination = false)this.localDataSource = r.data; // 返回结果中的数组数据this.localLoading = false});}},initTotalList(columns) {const totalList = []columns && columns instanceof Array && columns.forEach(column => {if (column.needTotal) {totalList.push({...column,total: 0})}})return totalList},updateSelect(selectedRowKeys, selectedRows) {this.selectedRowKeys = selectedRowKeysthis.selectedRows = selectedRowslet list = this.needTotalListthis.needTotalList = list.map(item => {return {...item,total: selectedRows.reduce((sum, val) => {let total = sum + get(val, item.dataIndex)return isNaN(total) ? 0 : total}, 0)}})},updateEdit() {this.selectedRows = []},onClearSelected() {this.selectedRowKeys = []this.selectedRows = []this.updateSelect([], [])this.$emit('emptyData', { selectedRowKeys: [], selectedRows: [] })this.$emit('onSelect', { selectedRowKeys: [], selectedRows: [] })},onDeleteSelected() {this.$emit('DeleteData')},handleRowClick(record) {const selectedRowKeys = [...this.selectedRowKeys];const selectedRows = [...this.selectedRows];const rowKey = typeof this.rowKey === 'function' ? this.rowKey(record) : record[this.rowKey];const rowIndex = selectedRowKeys.indexOf(rowKey);if (rowIndex >= 0) {selectedRowKeys.splice(rowIndex, 1);selectedRows.splice(rowIndex, 1);} else {selectedRowKeys.push(rowKey);selectedRows.push(record);}this.updateSelect(selectedRowKeys, selectedRows);this.$emit('onSelect', { selectedRowKeys, selectedRows });},renderMsg(h) {const _vm = thisthis.that = thislet d = []return d},renderAlert(h) {return h('span', {slot: 'message'}, this.renderMsg(h))},},render(h) {const _vm = thislet props = {},localKeys = Object.keys(this.$data);Object.keys(T.props).forEach(k => {let localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`;if (localKeys.includes(localKey)) {return props[k] = _vm[localKey];}return props[k] = _vm[k];})// 显示信息提示if (this.showAlertInfo) {props.rowSelection = {selectedRowKeys: this.selectedRowKeys,onChange: (selectedRowKeys, selectedRows) => {_vm.updateSelect(selectedRowKeys, selectedRows)_vm.$emit('onSelect', { selectedRowKeys: selectedRowKeys, selectedRows: selectedRows })}};props.customRow = (record) => ({on: {click: () => {_vm.handleRowClick(record);},},});return h('div', {}, [h("a-table", {tag: "component",attrs: props,on: {change: _vm.loadData},scopedSlots: this.$scopedSlots}, this.$slots.default)]);}props.customRow = (record) => ({on: {click: () => {_vm.handleRowClick(record);},},});return h("a-table", {tag: "component",attrs: props,on: {change: _vm.loadData},scopedSlots: this.$scopedSlots}, this.$slots.default);},
};
使用
<s-tableref="tableAssets"size="default":rowKey="(record) => record.id":columns="columns1":data="loadDataListAssets":showAlertInfo="true"@onSelect="onChangeAssetsList"></s-table>loadDataListAssets: (parameter) => {return getUserPage(Object.assign(parameter, this.listAssetsParam)).then((res) => {var mm = { data: [] };mm.size = res.data.size;mm.current = res.data.current;mm.totalCount = res.data.total;mm.totalPage = res.data.pages;mm.data = res.data.records;return mm;});},onChangeAssetsList(row) {console.log(row);let self = this;self.personList = [];let arr = [...new Set([...row.selectedRows])];let AssetsListRow = [...new Set([...self.AssetsListRow.concat(arr), ...arr]),];self.AssetsListRow = AssetsListRow.filter((item) =>row.selectedRowKeys.includes(item.id));self.personList = [...new Set([...self.AssetsListRow, ...arr])];// self.personList = [...new Set([...self.personList, ...arr])];// const strings = self.personList.map((item) => JSON.stringify(item));// const removeDupList = Array.from(new Set(strings));// const result = removeDupList.map((item) => JSON.parse(item));// self.personList = result;},
有slot使用
<s-table ref="tableAssets2" size="default" :columns="columns2" :data="loadDataListAssets2"><span slot="action" slot-scope="text, record" class="flx-row-c-c"><div><a @click="handleDel(record)">删除</a></div></span>
</s-table>
3.关于单选封装好的组件使用
<j-select-supplierv-decorator="['supplierId']":multiple="false"@accountData="accountData2"></j-select-supplier>import JSelectSupplier from "@/components/jeecgbiz/JSelectSupplier";accountData2(e) {if (e.length > 0) {this.editform.supplierName = e[0].name;this.editform.supplierId = e[0].id;} else {this.editform.supplierName = "";this.editform.supplierId = "";}console.log(e);},
<template><!-- 定义在这里的参数都是不可在外部覆盖的,防止出现问题 --><j-select-biz-component-two:value="value":ellipsisLength="25":listUrl="url.list":columns="columns":multiple="false"v-on="$listeners"v-bind="attrs"@commitData="commitData"/>
</template><script>
import JSelectBizComponentTwo from "./JSelectBizComponentTwo";export default {name: "JSelectSupplier",components: { JSelectBizComponentTwo },props: ["value"],data() {return {url: { list: "/asset/supplierinfo/page" },columns: [{ title: "供应商", align: "center", dataIndex: "name" },{title: "联系人",align: "center",dataIndex: "linkman",},{title: "联系电话",align: "center",dataIndex: "phone",},],// 定义在这里的参数都是可以在外部传递覆盖的,可以更灵活的定制化使用的组件default: {name: "供应商",width: "80%",displayKey: "name",returnKeys: ["id", "name"],rowKey: "id",valueKey: "id",queryParamText: "供应商名称", //左侧搜索框名称queryParamCode: "name", //左侧搜索框字段名},};},computed: {attrs() {return Object.assign(this.default, this.$attrs);},},methods: {// 提交数据commitData(e) {console.log(e);this.$emit("accountData", e);},},
};
</script><style lang="less" scoped></style>
外层也就是index
<template><a-row class="j-select-biz-component-box" type="flex" :gutter="8"><a-col class="left" :class="{'full': !buttons}"><slot name="left"><a-selectmode="multiple":placeholder="placeholder"v-model="selectValue":options="selectOptions"allowClear:disabled="disabled":open="selectOpen"style="width: 100%;"@dropdownVisibleChange="handleDropdownVisibleChange"@click.native="visible=(buttons?visible:true)"/></slot></a-col><a-col v-if="buttons" class="right"><a-button type="primary" icon="search" :disabled="disabled" @click="visible=true">{{selectButtonText}}</a-button></a-col><j-select-biz-component-modalv-model="selectValue":visible.sync="visible"v-bind="modalProps":multiple="multiple"@options="handleOptions"@commitData="commitData"/></a-row>
</template><script>import JSelectBizComponentModal from './JSelectBizComponentModal'export default {name: 'JSelectBizComponent',components: { JSelectBizComponentModal },props: {value: {type: String,default: ''},/** 是否返回 id,默认 false,返回 code */returnId: {type: Boolean,default: false},placeholder: {type: String,default: '请选择'},disabled: {type: Boolean,default: false},// 是否支持多选,默认 truemultiple: {type: Boolean,default: true},// 是否显示按钮,默认 truebuttons: {type: Boolean,default: true},// 显示的 KeydisplayKey: {type: String,default: null},// 返回的 keyreturnKeys: {type: Array,default: () => ['id', 'id']},// 选择按钮文字selectButtonText: {type: String,default: '选择'},},data() {return {selectValue: [],selectOptions: [],dataSourceMap: {},visible: false,selectOpen: false,}},computed: {valueKey() {return this.returnId ? this.returnKeys[0] : this.returnKeys[1]},modalProps() {return Object.assign({valueKey: this.valueKey,multiple: this.multiple,returnKeys: this.returnKeys,displayKey: this.displayKey || this.valueKey}, this.$attrs)},},watch: {value: {immediate: true,handler(val) {console.log('cake撒',val)if (val) {this.selectValue = val.split(',')} else {this.selectValue = []}}},selectValue: {deep: true,handler(val) {console.log(this.materialUseTime)let rows = val.map(key => this.dataSourceMap[key])this.$emit('select', rows)let data = val.join(',')this.$emit('input', data)this.$emit('change', data)}}},methods: {commitData(e) {this.$emit('commitData',e)},handleOptions(options, dataSourceMap) {this.selectOptions = optionsthis.dataSourceMap = dataSourceMap},handleDropdownVisibleChange() {// 解决antdv自己的bug —— open 设置为 false 了,点击后还是添加了 open 样式,导致点击事件失效this.selectOpen = truethis.$nextTick(() => {this.selectOpen = false})},}}
</script><style lang="less" scoped>.j-select-biz-component-box {@width: 82px;.left {width: calc(100% - @width - 8px);}.right {width: @width;}.full {width: 100%;}/deep/ .ant-select-search__field {display: none !important;}}
</style>
内层
<template><a-modalcentered:title="name + '选择'":width="width":visible="visible"@ok="handleOk"@cancel="close"cancelText="关闭"><a-row :gutter="18"><a-col :span="16"><!-- 查询区域 --><div class="table-page-search-wrapper"><a-form layout="inline"><a-row :gutter="24"><a-col :span="14"><a-form-item :label="queryParamText || name"><a-inputv-model="queryParam[queryParamCode || valueKey]":placeholder="'请输入' + (queryParamText || name)"@pressEnter="searchQuery"/></a-form-item></a-col><a-col :span="8"><spanstyle="float: left; overflow: hidden"class="table-page-search-submitButtons"><a-button type="primary" @click="searchQuery" icon="search">查询</a-button><a-buttontype="primary"@click="searchReset"icon="reload"style="margin-left: 8px">重置</a-button></span></a-col></a-row></a-form></div><a-tablesize="small"bordered:rowKey="rowKey":columns="innerColumns":dataSource="dataSource":pagination="ipagination":loading="loading":scroll="{ y: 240 }":rowSelection="{selectedRowKeys,onChange: onSelectChange,type: multiple ? 'checkbox' : 'radio',width: '60px',}":customRow="customRowFn"@change="handleTableChange"></a-table></a-col><a-col :span="8"><a-card:title="'已选中的' + name":bordered="false":head-style="{ padding: 0 }":body-style="{ padding: 0 }"><a-tablesize="small":rowKey="rowKey"borderedv-bind="selectedTable"><span slot="action" slot-scope="text, record, index"><a @click="handleDeleteSelected(record, index)">删除</a></span></a-table></a-card></a-col></a-row></a-modal>
</template><script>
// import { getAction } from '@/api/manage'
import Ellipsis from "@/components/Ellipsis";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { cloneObject, pushIfNotExist } from "@/utils/util";export default {name: "JSelectBizComponentModal",mixins: [JeecgListMixin],components: { Ellipsis },props: {value: {type: Array,default: () => [],},visible: {type: Boolean,default: false,},valueKey: {type: String,required: true,},multiple: {type: Boolean,default: true,},width: {type: [Number, String],default: "80%",},name: {type: String,default: "",},listUrl: {type: String,required: true,default: "",},// 根据 value 获取显示文本的地址,例如存的是 username,可以通过该地址获取到 realnamevalueUrl: {type: String,default: "",},displayKey: {type: String,default: null,},columns: {type: Array,required: true,default: () => [],},// 查询条件CodequeryParamCode: {type: String,default: null,},// 查询条件文字queryParamText: {type: String,default: null,},rowKey: {type: String,default: "id",},// 过长裁剪长度,设置为 -1 代表不裁剪ellipsisLength: {type: Number,default: 12,},},data() {return {innerValue: [],// 已选择列表selectedTable: {pagination: false,scroll: { y: 240 },columns: [{...this.columns[0],width: this.columns[0].widthRight || this.columns[0].width,},{...this.columns[1],width: this.columns[1].widthRight || this.columns[1].width,},{title: "操作",dataIndex: "action",align: "center",width: 60,scopedSlots: { customRender: "action" },},],dataSource: [],},renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),url: { list: this.listUrl },/* 分页参数 */ipagination: {current: 1,pageSize: 5,pageSizeOptions: ["5", "10", "20", "30"],showTotal: (total, range) => {return range[0] + "-" + range[1] + " 共" + total + "条";},showQuickJumper: true,showSizeChanger: true,total: 0,},options: [],dataSourceMap: {},};},computed: {// 表头innerColumns() {let columns = cloneObject(this.columns);columns.forEach((column) => {// 给所有的列加上过长裁剪if (this.ellipsisLength !== -1) {column.customRender = (text) => this.renderEllipsis(text);}});return columns;},},watch: {value: {deep: true,immediate: true,handler(val) {console.log(val);this.innerValue = cloneObject(val);this.selectedRowKeys = [];this.valueWatchHandler(val);this.queryOptionsByValue(val);},},dataSource: {deep: true,handler(val) {// 重置之后key恢复this.emitOptions(val);this.valueWatchHandler(this.innerValue);},},selectedRowKeys: {immediate: true,deep: true,handler(val) {this.selectedTable.dataSource = val.map((key) => {for (let data of this.dataSource) {if (data[this.rowKey] === key) {pushIfNotExist(this.innerValue, data[this.valueKey]);return data;}}for (let data of this.selectedTable.dataSource) {if (data[this.rowKey] === key) {pushIfNotExist(this.innerValue, data[this.valueKey]);return data;}}console.warn("未找到选择的行信息,key:" + key);return {};});},},},methods: {/** 关闭弹窗 */close() {this.$emit("update:visible", false);},valueWatchHandler(val) {console.log(val);val.forEach((item) => {this.dataSource.concat(this.selectedTable.dataSource).forEach((data) => {if (data[this.valueKey] === item) {pushIfNotExist(this.selectedRowKeys, data[this.rowKey]);}});});},queryOptionsByValue(value) {console.log(value);if (!value || value.length === 0) {return;}// 判断options是否存在value,如果已存在数据就不再请求后台了let notExist = false;for (let val of value) {let find = false;for (let option of this.options) {if (val === option.value) {find = true;break;}}if (!find) {notExist = true;break;}}if (!notExist) return;// listDepartUser( {// // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询,防止后台进行了模糊匹配,导致查询结果不准确// // [this.valueKey]: value.join(',') + ',',// pageNo: 1,// pageSize: value.length// }).then((res) => {// if (res.success) {// let dataSource = res.result// if (!(dataSource instanceof Array)) {// dataSource = res.result.records// }// this.emitOptions(dataSource, (data) => {// pushIfNotExist(this.innerValue, data[this.valueKey])// pushIfNotExist(this.selectedRowKeys, data[this.rowKey])// pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)// })// }// })},emitOptions(dataSource, callback) {dataSource.forEach((data) => {let key = data[this.valueKey];this.dataSourceMap[key] = data;pushIfNotExist(this.options,{ label: data[this.displayKey || this.valueKey], value: key },"value");typeof callback === "function" ? callback(data) : "";});this.$emit("options", this.options, this.dataSourceMap);},/** 完成选择 */handleOk() {let value = this.selectedTable.dataSource.map((data) => data[this.valueKey]);this.$emit("input", value);this.$emit("commitData", this.selectedTable.dataSource);this.close();},/** 删除已选择的 */handleDeleteSelected(record, index) {this.selectionRows.splice(this.selectedRowKeys.indexOf(record[this.rowKey]),1);this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]),1);this.selectedTable.dataSource.splice(index, 1);console.log(this.selectedRowKeys, this.selectionRows);},customRowFn(record) {return {on: {click: () => {let key = record[this.rowKey];if (!this.multiple) {this.selectedRowKeys = [key];this.selectedTable.dataSource = [record];} else {let index = this.selectedRowKeys.indexOf(key);if (index === -1) {this.selectedRowKeys.push(key);this.selectedTable.dataSource.push(record);} else {this.handleDeleteSelected(record, index);}}},},};},},
};
</script>
<style lang="less" scoped>
</style>
JeecgListMixin的方法
/*** 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm* 高级查询按钮调用 superQuery方法 高级查询组件ref定义为superQueryModal* data中url定义 list为查询列表 delete为删除单条记录 deleteBatch为批量删除*/
import { filterObj } from "@/utils/util";
import { deleteAction, getAction, downFile, getFileAccessHttpUrl } from "@/api/manage";export const JeecgListMixin = {data() {return {/* 查询条件-请不要在queryParam中声明非字符串值的属性 */queryParam: {},/* 数据源 */dataSource: [],/* 分页参数 */ipagination: {current: 1,pageSize: 10,pageSizeOptions: ["10", "20", "30"],showTotal: (total, range) => {return range[0] + "-" + range[1] + " 共" + total + "条";},showQuickJumper: true,showSizeChanger: true,total: 0,},/* 排序参数 */isorter: {column: "createTime",order: "desc",},/* 筛选参数 */filters: {},/* table加载状态 */loading: false,/* table选中keys*/selectedRowKeys: [],/* table选中records*/selectionRows: [],/* 查询折叠 */toggleSearchStatus: false,/* 高级查询条件生效状态 */superQueryFlag: false,/* 高级查询条件 */superQueryParams: "",/** 高级查询拼接方式 */superQueryMatchType: "and",};},created() {if (!this.disableMixinCreated) {console.log(" -- mixin created -- ");this.loadData();//初始化字典配置 在自己页面定义this.initDictConfig();}},computed: {},methods: {loadData(arg) {if (!this.url.list) {this.$message.error("请设置url.list属性!");return;}//加载数据 若传入参数1则加载第一页的内容if (arg === 1) {this.ipagination.current = 1;}var params = this.getQueryParams(); //查询条件this.loading = true;getAction(this.url.list, params).then((res) => {if (res.ok) {//update-begin---author:zhangyafei Date:20201118 for:适配不分页的数据列表------------this.dataSource = res.data.records || res.data;if (res.data.total) {this.ipagination.total = res.data.total;} else {this.ipagination.total = 0;}//update-end---author:zhangyafei Date:20201118 for:适配不分页的数据列表------------} else {this.$message.warning(res.msg);}}).finally(() => {this.loading = false;});},initDictConfig() {console.log("--这是一个假的方法!");},handleSuperQuery(params, matchType) {//高级查询方法if (!params) {this.superQueryParams = "";this.superQueryFlag = false;} else {this.superQueryFlag = true;this.superQueryParams = JSON.stringify(params);this.superQueryMatchType = matchType;}this.loadData(1);},getQueryParams() {//获取查询条件let sqp = {};if (this.superQueryParams) {sqp["superQueryParams"] = encodeURI(this.superQueryParams);sqp["superQueryMatchType"] = this.superQueryMatchType;}var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);// param.field = this.getQueryField();param.current = this.ipagination.current;param.size = this.ipagination.pageSize;return filterObj(param);},getQueryField() {//TODO 字段权限控制var str = "id,";this.columns.forEach(function (value) {str += "," + value.dataIndex;});return str;},onSelectChange(selectedRowKeys, selectionRows) {this.selectedRowKeys = selectedRowKeys;this.selectionRows = selectionRows;console.log(selectedRowKeys, selectionRows);},onClearSelected() {this.selectedRowKeys = [];this.selectionRows = [];},searchQuery() {this.loadData(1);},superQuery() {this.$refs.superQueryModal.show();},searchReset() {this.queryParam = {};this.loadData(1);},batchDel: function () {if (!this.url.deleteBatch) {this.$message.error("请设置url.deleteBatch属性!");return;}if (this.selectedRowKeys.length <= 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.reCalculatePage(that.selectedRowKeys.length);that.$message.success(res.message);that.loadData();that.onClearSelected();} else {that.$message.warning(res.message);}}).finally(() => {that.loading = false;});},});}},handleDelete: function (id) {if (!this.url.delete) {this.$message.error("请设置url.delete属性!");return;}var that = this;deleteAction(`${that.url.delete}/${id}`, { id: id }).then((res) => {if (res.ok) {//重新计算分页问题that.reCalculatePage(1);that.$message.success("操作成功");that.loadData();} else {that.$message.warning(res.msg);}});},reCalculatePage(count) {//总数量-countlet total = this.ipagination.total - count;//获取删除后的分页数let currentIndex = Math.ceil(total / this.ipagination.pageSize);//删除后的分页数<所在当前页if (currentIndex < this.ipagination.current) {this.ipagination.current = currentIndex;}console.log("currentIndex", currentIndex);},handleEdit: function (record) {this.$refs.modalForm.edit(record);this.$refs.modalForm.title = "编辑";this.$refs.modalForm.disableSubmit = false;},handleAdd: function () {this.$refs.modalForm.add();this.$refs.modalForm.title = "新增";this.$refs.modalForm.disableSubmit = false;},handleTableChange(pagination, filters, sorter) {//分页、排序、筛选变化时触发//TODO 筛选console.log(pagination);if (Object.keys(sorter).length > 0) {// this.isorter.column = sorter.field;this.isorter.order = "ascend" == sorter.order ? "asc" : "desc";}this.ipagination = pagination;this.loadData();},handleToggleSearch() {this.toggleSearchStatus = !this.toggleSearchStatus;},// 给popup查询使用(查询区域不支持回填多个字段,限制只返回一个字段)getPopupField(fields) {return fields.split(",")[0];},modalFormOk() {// 新增/修改 成功时,重载列表this.loadData();//清空列表选中this.onClearSelected();},handleDetail: function (record) {this.$refs.modalForm.edit(record);this.$refs.modalForm.title = "详情";this.$refs.modalForm.disableSubmit = true;},/* 导出 */handleExportXls2() {let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()));let url = `${window._CONFIG["domianURL"]}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`;window.location.href = url;},handleExportXls(fileName) {if (!fileName || typeof fileName != "string") {fileName = "导出文件";}let param = this.getQueryParams();if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {param["selections"] = this.selectedRowKeys.join(",");}console.log("导出参数", param);downFile(this.url.exportXlsUrl, param).then((data) => {if (!data) {this.$message.warning("文件下载失败");return;}if (typeof window.navigator.msSaveBlob !== "undefined") {window.navigator.msSaveBlob(new Blob([data], { type: "application/vnd.ms-excel" }), fileName + ".xls");} else {console.log(data);let url = window.URL.createObjectURL(new Blob([data.data], { type: "application/vnd.ms-excel" }));let link = document.createElement("a");link.style.display = "none";link.href = url;link.setAttribute("download", fileName + ".xls");document.body.appendChild(link);link.click();document.body.removeChild(link); //下载完成移除元素window.URL.revokeObjectURL(url); //释放掉blob对象}});},/* 图片预览 */getImgView(text) {if (text && text.indexOf(",") > 0) {text = text.substring(0, text.indexOf(","));}return getFileAccessHttpUrl(text);},/* 文件下载 */// update--autor:lvdandan-----date:20200630------for:修改下载文件方法名uploadFile改为downloadFile------downloadFile(text) {if (!text) {this.$message.warning("未知的文件");return;}if (text.indexOf(",") > 0) {text = text.substring(0, text.indexOf(","));}let url = getFileAccessHttpUrl(text);window.open(url);},},
};
Ellipsis的方法
import Ellipsis from './Ellipsis'export default Ellipsis
Ellipsis.vue
<script>import { cutStrByFullLength, getStrFullLength } from '@/components/_util/StringUtil'export default {name: 'Ellipsis',props: {prefixCls: {type: String,default: 'ant-pro-ellipsis'},tooltip: {type: Boolean,default: true,},length: {type: Number,default: 25,},lines: {type: Number,default: 1},fullWidthRecognition: {type: Boolean,default: false}},methods: {},render() {const { tooltip, length } = this.$propslet text = ''// 处理没有default插槽时的特殊情况if (this.$slots.default) {text = this.$slots.default.map(vNode => vNode.text).join('')}// 判断是否显示 tooltipif (tooltip && getStrFullLength(text) > length) {return (<a-tooltip><template slot="title">{text}</template><span>{cutStrByFullLength(text, this.length) + '…'}</span></a-tooltip>)} else {return (<span>{text}</span>)}}}
</script>
4.关于封装好的复选表格
<j-select-contract:trigger-change="true"v-decorator="['purchaseContractIds']"customReturnField="purchaseContractIds"@accountData="changeContract":multiple="true":status="2"></j-select-contract>
import JSelectContract from "@/components/jeecgbiz/JSelectContract";
<template><!-- 定义在这里的参数都是不可在外部覆盖的,防止出现问题 --><j-select-biz-component:value="value":ellipsisLength="25":listUrl="url.list":columns="columns":multiple="multiple"v-on="$listeners"v-bind="attrs"@commitData="commitData"/>
</template><script>
import JSelectBizComponent from "./JSelectBizComponent";export default {name: "JSelectContract",components: { JSelectBizComponent },props: ["value", "multiple"],data() {return {url: { list: "/asset/purchasecontract/page?contractStatus=2&isAllTake=0" },columns: [{ title: "合同单据号", align: "center", width: "25%", widthRight: "70%", dataIndex: "purchaseContractNo" },{ title: "订购时间", align: "center", width: "25%", dataIndex: "orderDate" },{ title: "采购员", align: "center", width: "20%", dataIndex: "purchasePersonName" },{ title: "采购部门", align: "center", width: "20%", dataIndex: "organName" },],// 定义在这里的参数都是可以在外部传递覆盖的,可以更灵活的定制化使用的组件default: {name: "采购合同",width: 1200,displayKey: "purchaseContractNo",returnKeys: ["id", "purchaseContractNo", "organName", "organId"],queryParamText: "合同单据号",queryParamCode: "purchaseContractNo",},};},computed: {attrs() {return Object.assign(this.default, this.$attrs);},},methods: {// 提交数据commitData(e) {this.$emit("accountData", e);},},
};
</script><style lang="less" scoped></style>
index外层
<template><a-row class="j-select-biz-component-box" type="flex" :gutter="8"><a-col class="left" :class="{'full': !buttons}"><slot name="left"><a-selectmode="multiple":placeholder="placeholder"v-model="selectValue":options="selectOptions"allowClear:disabled="disabled":open="selectOpen"style="width: 100%;"@dropdownVisibleChange="handleDropdownVisibleChange"@click.native="visible=(buttons?visible:true)"/></slot></a-col><a-col v-if="buttons" class="right"><a-button type="primary" icon="search" :disabled="disabled" @click="visible=true">{{selectButtonText}}</a-button></a-col><j-select-biz-component-modalv-model="selectValue":visible.sync="visible"v-bind="modalProps":multiple="multiple"@options="handleOptions"@commitData="commitData"/></a-row>
</template><script>import JSelectBizComponentModal from './JSelectBizComponentModal'export default {name: 'JSelectBizComponent',components: { JSelectBizComponentModal },props: {value: {type: String,default: ''},/** 是否返回 id,默认 false,返回 code */returnId: {type: Boolean,default: false},placeholder: {type: String,default: '请选择'},disabled: {type: Boolean,default: false},// 是否支持多选,默认 truemultiple: {type: Boolean,default: true},// 是否显示按钮,默认 truebuttons: {type: Boolean,default: true},// 显示的 KeydisplayKey: {type: String,default: null},// 返回的 keyreturnKeys: {type: Array,default: () => ['id', 'id']},// 选择按钮文字selectButtonText: {type: String,default: '选择'},},data() {return {selectValue: [],selectOptions: [],dataSourceMap: {},visible: false,selectOpen: false,}},computed: {valueKey() {return this.returnId ? this.returnKeys[0] : this.returnKeys[1]},modalProps() {return Object.assign({valueKey: this.valueKey,multiple: this.multiple,returnKeys: this.returnKeys,displayKey: this.displayKey || this.valueKey}, this.$attrs)},},watch: {value: {immediate: true,handler(val) {console.log('cake撒',val)if (val) {this.selectValue = val.split(',')} else {this.selectValue = []}}},selectValue: {deep: true,handler(val) {console.log(this.materialUseTime)let rows = val.map(key => this.dataSourceMap[key])this.$emit('select', rows)let data = val.join(',')this.$emit('input', data)this.$emit('change', data)}}},methods: {commitData(e) {this.$emit('commitData',e)},handleOptions(options, dataSourceMap) {this.selectOptions = optionsthis.dataSourceMap = dataSourceMap},handleDropdownVisibleChange() {// 解决antdv自己的bug —— open 设置为 false 了,点击后还是添加了 open 样式,导致点击事件失效this.selectOpen = truethis.$nextTick(() => {this.selectOpen = false})},}}
</script><style lang="less" scoped>.j-select-biz-component-box {@width: 82px;.left {width: calc(100% - @width - 8px);}.right {width: @width;}.full {width: 100%;}/deep/ .ant-select-search__field {display: none !important;}}
</style>
内层
<template><a-modalcentered:title="name + '选择'":width="width":visible="visible"@ok="handleOk"@cancel="close"cancelText="关闭"><a-row :gutter="18"><a-col :span="16"><!-- 查询区域 --><div class="table-page-search-wrapper"><a-form :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }"><a-row :gutter="24"><a-col :span="14"><a-form-item :label="queryParamText || name"><a-inputv-model="queryParam[queryParamCode || valueKey]":placeholder="'请输入' + (queryParamText || name)"@pressEnter="searchQuery"/></a-form-item></a-col><a-col :span="8"><spanstyle="float: left; overflow: hidden"class="table-page-search-submitButtons"><a-button type="primary" @click="searchQuery" icon="search">查询</a-button><a-buttontype="primary"@click="searchReset"icon="reload"style="margin-left: 8px">重置</a-button></span></a-col></a-row></a-form></div><a-tablesize="small"bordered:rowKey="rowKey":columns="innerColumns":dataSource="dataSource":pagination="ipagination":loading="loading":scroll="{ y: 240 }":rowSelection="{selectedRowKeys,onChange: onSelectChange,type: multiple ? 'checkbox' : 'radio',}":customRow="customRowFn"@change="handleTableChange"></a-table></a-col><a-col :span="8"><a-card:title="'已选' + name":bordered="false":head-style="{ padding: 0 }":body-style="{ padding: 0 }"><a-tablesize="small":rowKey="rowKey"borderedv-bind="selectedTable"><span slot="action" slot-scope="text, record, index"><a @click="handleDeleteSelected(record, index)">删除</a></span></a-table></a-card></a-col></a-row></a-modal>
</template><script>
// import { getAction } from '@/api/manage'
import Ellipsis from "@/components/Ellipsis";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { cloneObject, pushIfNotExist } from "@/utils/util";
import { listDepartUser } from "@/api/apis";export default {name: "JSelectBizComponentModal",mixins: [JeecgListMixin],components: { Ellipsis },props: {value: {type: Array,default: () => [],},visible: {type: Boolean,default: false,},valueKey: {type: String,required: true,},multiple: {type: Boolean,default: true,},width: {type: Number,default: 900,},name: {type: String,default: "",},listUrl: {type: String,required: true,default: "",},// 根据 value 获取显示文本的地址,例如存的是 username,可以通过该地址获取到 realnamevalueUrl: {type: String,default: "",},displayKey: {type: String,default: null,},columns: {type: Array,required: true,default: () => [],},// 查询条件CodequeryParamCode: {type: String,default: null,},// 查询条件文字queryParamText: {type: String,default: null,},rowKey: {type: String,default: "id",},// 过长裁剪长度,设置为 -1 代表不裁剪ellipsisLength: {type: Number,default: 12,},},data() {return {innerValue: [],// 已选择列表selectedTable: {pagination: false,scroll: { y: 240 },columns: [{...this.columns[0],width: this.columns[0].widthRight || this.columns[0].width,},{title: "操作",dataIndex: "action",align: "center",width: 60,scopedSlots: { customRender: "action" },},],dataSource: [],},renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),url: { list: this.listUrl },/* 分页参数 */ipagination: {current: 1,pageSize: 5,pageSizeOptions: ["5", "10", "20", "30"],showTotal: (total, range) => {return range[0] + "-" + range[1] + " 共" + total + "条";},showQuickJumper: true,showSizeChanger: true,total: 0,},options: [],dataSourceMap: {},};},computed: {// 表头innerColumns() {let columns = cloneObject(this.columns);columns.forEach((column) => {// 给所有的列加上过长裁剪if (this.ellipsisLength !== -1) {column.customRender = (text) => this.renderEllipsis(text);}});return columns;},},watch: {value: {deep: true,immediate: true,handler(val) {console.log(val);this.innerValue = cloneObject(val);this.selectedRowKeys = [];this.valueWatchHandler(val);this.queryOptionsByValue(val);},},dataSource: {deep: true,handler(val) {// 重置之后key恢复this.emitOptions(val);this.valueWatchHandler(this.innerValue);},},selectedRowKeys: {immediate: true,deep: true,handler(val) {this.selectedTable.dataSource = val.map((key) => {for (let data of this.dataSource) {if (data[this.rowKey] === key) {pushIfNotExist(this.innerValue, data[this.valueKey]);return data;}}for (let data of this.selectedTable.dataSource) {if (data[this.rowKey] === key) {pushIfNotExist(this.innerValue, data[this.valueKey]);return data;}}console.warn("未找到选择的行信息,key:" + key);return {};});},},},methods: {/** 关闭弹窗 */close() {this.$emit("update:visible", false);},valueWatchHandler(val) {console.log(val);val.forEach((item) => {this.dataSource.concat(this.selectedTable.dataSource).forEach((data) => {if (data[this.valueKey] === item) {pushIfNotExist(this.selectedRowKeys, data[this.rowKey]);}});});},queryOptionsByValue(value) {console.log(value);if (!value || value.length === 0) {return;}// 判断options是否存在value,如果已存在数据就不再请求后台了let notExist = false;for (let val of value) {let find = false;for (let option of this.options) {if (val === option.value) {find = true;break;}}if (!find) {notExist = true;break;}}if (!notExist) return;// listDepartUser( {// // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询,防止后台进行了模糊匹配,导致查询结果不准确// // [this.valueKey]: value.join(',') + ',',// pageNo: 1,// pageSize: value.length// }).then((res) => {// if (res.success) {// let dataSource = res.result// if (!(dataSource instanceof Array)) {// dataSource = res.result.records// }// this.emitOptions(dataSource, (data) => {// pushIfNotExist(this.innerValue, data[this.valueKey])// pushIfNotExist(this.selectedRowKeys, data[this.rowKey])// pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)// })// }// })},emitOptions(dataSource, callback) {dataSource.forEach((data) => {let key = data[this.valueKey];this.dataSourceMap[key] = data;pushIfNotExist(this.options,{ label: data[this.displayKey || this.valueKey], value: key },"value");typeof callback === "function" ? callback(data) : "";});this.$emit("options", this.options, this.dataSourceMap);},/** 完成选择 */handleOk() {let value = this.selectedTable.dataSource.map((data) => data[this.valueKey]);this.$emit("input", value);console.log(this.selectedTable.dataSource);this.$emit("commitData", this.selectedTable.dataSource);this.close();},/** 删除已选择的 */handleDeleteSelected(record, index) {this.selectionRows.splice(this.selectedRowKeys.indexOf(record[this.rowKey]),1);this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]),1);this.selectedTable.dataSource.splice(index, 1);console.log(this.selectedRowKeys, this.selectionRows);},customRowFn(record) {return {on: {click: () => {let key = record[this.rowKey];if (!this.multiple) {this.selectedRowKeys = [key];this.selectedTable.dataSource = [record];} else {let index = this.selectedRowKeys.indexOf(key);if (index === -1) {this.selectedRowKeys.push(key);this.selectedTable.dataSource.push(record);} else {this.handleDeleteSelected(record, index);}}},},};},},
};
</script>
<style lang="less" scoped>
</style>
这边的方法通单选框是一样的
5.关于没有封装的单选框表格同时要实现点击行增加单选框选中效果
<a-tablestyle="width: 100%; margin-top: 50px":rowKey="(record) => record.id":dataSource="tableData":columns="columns":row-selection="{type: 'radio',onChange: onSelectChange,selectedRowKeys: selectedRowKeys,}":customRow="customRowFn"@change="handleTableChange":pagination="ipagination":loading="tableLoading"bordered></a-table>
data(){
return{tableSelectRow: {},selectedRowKeys: [],/* 分页参数 */ipagination: {current: 1,pageSize: 10,total: 0,},
}
}method:{
//控制单选框onSelectChange(val, row) {console.log("val", val, "row", row);this.tableSelectRow = row[0];this.selectedRowKeys = val;},
//控制行customRowFn属性customRowFn(record) {return {on: {click: () => {// console.log("record", record);this.tableSelectRow = record;this.selectedRowKeys = [record.id];// console.log("this.tableSelectRow", this.tableSelectRow);// console.log("this.selectedRowKeys", this.selectedRowKeys);},},};},handleTableChange(pagination) {//分页、排序、筛选变化时触发this.ipagination = pagination;this.getlistassetstandardmodel();},
}// 资产型号确定chosmodelok() {console.log(this.assetsData);console.log(this.tableSelectRow);this.form.setFieldsValue({assetName: this.tableSelectRow.standardName,categoryId: this.tableSelectRow.categoryId,assetModel: this.tableSelectRow.standardModel,assetMetering: this.tableSelectRow.standardMetering,});(this.assetsData.categoryName = this.tableSelectRow.categoryName),(this.chosmodel = false);},
6.关于没有封装的单选框表格同时要实现点击行增加多选框选中效果
<a-table:columns="columns":data-source="dataSource"size="small"rowKey="id":loading="loading":pagination="ipagination"bordered:rowSelection="{selectedRowKeys: selectedRowKeys,onChange: onChangeTableSelect,}":customRow="customRowFn"@change="handleTableChange">
selectedRowKeys: [],selectionRows: [],
methods: {customRowFn(record) {return {on: {click: () => {// console.log("record", record);// this.tableSelectRow = record;// this.selectedRowKeys = [record.id];// console.log("this.tableSelectRow", this.tableSelectRow);// console.log("this.selectedRowKeys", this.selectedRowKeys);let key = record.id;let index = this.selectedRowKeys.indexOf(key);// console.log("index", index);if (index === -1) {this.selectedRowKeys.push(key);this.selectionRows.push(record);} else {this.selectionRows.splice(this.selectionRows.indexOf(record.id),1);this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record.id),1);}console.log("this.selectionRows", this.selectionRows);},},};},onChangeTableSelect(selectedRowKeys, selectionRows) {this.selectedRowKeys = selectedRowKeys;let mRow = JSON.parse(JSON.stringify(this.selectionRows));selectionRows.forEach((item) => {pushIfNotExist(mRow, item, "id");});this.selectionRows = this.selectedRowKeys.map((item) => {let mObj = {};mRow.forEach((items) => {if (items.id == item) {mObj = items;}});console.log(mObj);return mObj;});console.log(this.selectionRows);},clickShowModal(rows) {let mRows = JSON.parse(JSON.stringify(rows));this.onClearSelected();this.selectedRowKeys = mRows.map((item) => item.id);this.selectionRows = mRows;this.visible = true;this.loadData(1);},handleOk() {this.visible = false;this.$emit("select",JSON.parse(JSON.stringify(this.selectedRowKeys)),JSON.parse(JSON.stringify(this.selectionRows)));},},
};
这边表格分页效果是来自JeecgListMixin这个组件或者看5那边有单独写出来分页
/*** 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm* 高级查询按钮调用 superQuery方法 高级查询组件ref定义为superQueryModal* data中url定义 list为查询列表 delete为删除单条记录 deleteBatch为批量删除*/
import { filterObj } from "@/utils/util";
import { deleteAction, getAction, downFile, getFileAccessHttpUrl } from "@/api/manage";export const JeecgListMixin = {data() {return {/* 查询条件-请不要在queryParam中声明非字符串值的属性 */queryParam: {},/* 数据源 */dataSource: [],/* 分页参数 */ipagination: {current: 1,pageSize: 10,pageSizeOptions: ["10", "20", "30"],showTotal: (total, range) => {return range[0] + "-" + range[1] + " 共" + total + "条";},showQuickJumper: true,showSizeChanger: true,total: 0,},/* 排序参数 */isorter: {column: "createTime",order: "desc",},/* 筛选参数 */filters: {},/* table加载状态 */loading: false,/* table选中keys*/selectedRowKeys: [],/* table选中records*/selectionRows: [],/* 查询折叠 */toggleSearchStatus: false,/* 高级查询条件生效状态 */superQueryFlag: false,/* 高级查询条件 */superQueryParams: "",/** 高级查询拼接方式 */superQueryMatchType: "and",};},created() {if (!this.disableMixinCreated) {console.log(" -- mixin created -- ");this.loadData();//初始化字典配置 在自己页面定义this.initDictConfig();}},computed: {},methods: {loadData(arg) {if (!this.url.list) {this.$message.error("请设置url.list属性!");return;}//加载数据 若传入参数1则加载第一页的内容if (arg === 1) {this.ipagination.current = 1;}var params = this.getQueryParams(); //查询条件this.loading = true;getAction(this.url.list, params).then((res) => {if (res.ok) {//update-begin---author:zhangyafei Date:20201118 for:适配不分页的数据列表------------this.dataSource = res.data.records || res.data;if (res.data.total) {this.ipagination.total = res.data.total;} else {this.ipagination.total = 0;}//update-end---author:zhangyafei Date:20201118 for:适配不分页的数据列表------------} else {this.$message.warning(res.msg);}}).finally(() => {this.loading = false;});},initDictConfig() {console.log("--这是一个假的方法!");},handleSuperQuery(params, matchType) {//高级查询方法if (!params) {this.superQueryParams = "";this.superQueryFlag = false;} else {this.superQueryFlag = true;this.superQueryParams = JSON.stringify(params);this.superQueryMatchType = matchType;}this.loadData(1);},getQueryParams() {//获取查询条件let sqp = {};if (this.superQueryParams) {sqp["superQueryParams"] = encodeURI(this.superQueryParams);sqp["superQueryMatchType"] = this.superQueryMatchType;}var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);// param.field = this.getQueryField();param.current = this.ipagination.current;param.size = this.ipagination.pageSize;return filterObj(param);},getQueryField() {//TODO 字段权限控制var str = "id,";this.columns.forEach(function (value) {str += "," + value.dataIndex;});return str;},onSelectChange(selectedRowKeys, selectionRows) {this.selectedRowKeys = selectedRowKeys;this.selectionRows = selectionRows;console.log(selectedRowKeys, selectionRows);},onClearSelected() {this.selectedRowKeys = [];this.selectionRows = [];},searchQuery() {this.loadData(1);},superQuery() {this.$refs.superQueryModal.show();},searchReset() {this.queryParam = {};this.loadData(1);},batchDel: function () {if (!this.url.deleteBatch) {this.$message.error("请设置url.deleteBatch属性!");return;}if (this.selectedRowKeys.length <= 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.reCalculatePage(that.selectedRowKeys.length);that.$message.success(res.message);that.loadData();that.onClearSelected();} else {that.$message.warning(res.message);}}).finally(() => {that.loading = false;});},});}},handleDelete: function (id) {if (!this.url.delete) {this.$message.error("请设置url.delete属性!");return;}var that = this;deleteAction(`${that.url.delete}/${id}`, { id: id }).then((res) => {if (res.ok) {//重新计算分页问题that.reCalculatePage(1);that.$message.success("操作成功");that.loadData();} else {that.$message.warning(res.msg);}});},reCalculatePage(count) {//总数量-countlet total = this.ipagination.total - count;//获取删除后的分页数let currentIndex = Math.ceil(total / this.ipagination.pageSize);//删除后的分页数<所在当前页if (currentIndex < this.ipagination.current) {this.ipagination.current = currentIndex;}console.log("currentIndex", currentIndex);},handleEdit: function (record) {this.$refs.modalForm.edit(record);this.$refs.modalForm.title = "编辑";this.$refs.modalForm.disableSubmit = false;},handleAdd: function () {this.$refs.modalForm.add();this.$refs.modalForm.title = "新增";this.$refs.modalForm.disableSubmit = false;},handleTableChange(pagination, filters, sorter) {//分页、排序、筛选变化时触发//TODO 筛选console.log(pagination);if (Object.keys(sorter).length > 0) {// this.isorter.column = sorter.field;this.isorter.order = "ascend" == sorter.order ? "asc" : "desc";}this.ipagination = pagination;this.loadData();},handleToggleSearch() {this.toggleSearchStatus = !this.toggleSearchStatus;},// 给popup查询使用(查询区域不支持回填多个字段,限制只返回一个字段)getPopupField(fields) {return fields.split(",")[0];},modalFormOk() {// 新增/修改 成功时,重载列表this.loadData();//清空列表选中this.onClearSelected();},handleDetail: function (record) {this.$refs.modalForm.edit(record);this.$refs.modalForm.title = "详情";this.$refs.modalForm.disableSubmit = true;},/* 导出 */handleExportXls2() {let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()));let url = `${window._CONFIG["domianURL"]}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`;window.location.href = url;},handleExportXls(fileName) {if (!fileName || typeof fileName != "string") {fileName = "导出文件";}let param = this.getQueryParams();if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {param["selections"] = this.selectedRowKeys.join(",");}console.log("导出参数", param);downFile(this.url.exportXlsUrl, param).then((data) => {if (!data) {this.$message.warning("文件下载失败");return;}if (typeof window.navigator.msSaveBlob !== "undefined") {window.navigator.msSaveBlob(new Blob([data], { type: "application/vnd.ms-excel" }), fileName + ".xls");} else {console.log(data);let url = window.URL.createObjectURL(new Blob([data.data], { type: "application/vnd.ms-excel" }));let link = document.createElement("a");link.style.display = "none";link.href = url;link.setAttribute("download", fileName + ".xls");document.body.appendChild(link);link.click();document.body.removeChild(link); //下载完成移除元素window.URL.revokeObjectURL(url); //释放掉blob对象}});},/* 图片预览 */getImgView(text) {if (text && text.indexOf(",") > 0) {text = text.substring(0, text.indexOf(","));}return getFileAccessHttpUrl(text);},/* 文件下载 */// update--autor:lvdandan-----date:20200630------for:修改下载文件方法名uploadFile改为downloadFile------downloadFile(text) {if (!text) {this.$message.warning("未知的文件");return;}if (text.indexOf(",") > 0) {text = text.substring(0, text.indexOf(","));}let url = getFileAccessHttpUrl(text);window.open(url);},},
};
7.打印和导出写法
// 打印资产标签列表
const printAssetList = (fileName, params) => downloadFile("/asset/warehousing/printAssetList", fileName, params, "pdf"); // 打印资产标签列表
//导出资产列表
const warehousingExport = (fileName, params) => downloadFile("/asset/assetsinfo/export", fileName, params, "get"); // 导出资产列表
// 打印资产clickAssetsPrint() {this.assetsPrintLoading = true;var mm = {};mm.id = this.selectedRows.map((item) => {return item.materialCode;});printAssetList("资产标签", mm).then((res) => {this.assetsPrintLoading = false;}).catch((err) => {this.assetsPrintLoading = false;});// this.$refs.barCode.transferData(this.selectedRows)},// 导出资产getWarehousingExport() {var mm = {};mm.id = this.selectedRows.map((item) => {return item.materialCode;});warehousingExport("资产列表", mm).then((res) => {// let execlName = "资产文件名称";// const buf = Buffer.from(res),// blob = new Blob([buf], { type: "application/vnd.ms-excel" }),// downloadElement = document.createElement('a'),// href = window.URL.createObjectURL(blob); // 创建下载的链接// downloadElement.href = href;// downloadElement.download = `${execlName}.xls`; // 下载后文件名// document.body.appendChild(downloadElement);// downloadElement.click(); // 点击下载// window.URL.revokeObjectURL(href); // 释放掉blob对象});},
8.显示已删除的供应商
<a-checkboxstyle="margin-left: 20px"@change="onChange":value="yesOfno">显示已删除的供应商</a-checkbox>
onChange(e) {this.yesOfno = e.target.checked;this.$refs.table.refresh(this.queryParam);},
<s-tableref="table"size="default":columns="columns":data="loadData"@onSelect="onChangeTableSelect"><span slot="action" slot-scope="text, record"><a @click="handleEdit(record)">编辑</a><a-divider type="vertical" /><a-popconfirm title="你确定要删除吗?" @confirm="deleteTable(record)"><a>删除</a></a-popconfirm></span></s-table>
refresh() {var mm = {current: 1,total: 0,size: this.pageSize,}this.loadData(mm);},
同时也有关于loadData传参查询
// 加载数据方法 必须为 Promise 对象loadData: (parameter) => {this.queryParam.delFlag = this.yesOfno ? 1 : "";return listSupplierinfo(Object.assign(parameter, this.queryParam)).then((res) => {console.log(res);var mm = { data: [] };mm.size = res.data.size;mm.current = res.data.current;mm.totalCount = res.data.total;mm.totalPage = res.data.pages;mm.data = res.data.records;return mm;});},
9.关于loadData传参查询
loadData: (parameter) => {return allotapplyPage(Object.assign(parameter, this.queryParam)).then((res) => {var mm = { data: [] };mm.size = res.data.size;mm.current = res.data.current;mm.totalCount = res.data.total;mm.totalPage = res.data.pages;mm.data = res.data.records;return mm;});},
相关文章:

关于vue2 antd 碰到的问题总结下
1.关于vue2 antd 视图更新问题 1.一种强制更新 Vue2是通过用Object…defineProperty来设置数据的getter和setter实现对数据和以及视图改变的监听的。对于数组和对象这种引用类型来说,getter和setter无法检测到它们内部的变化。用这种 this.$set(this.form, "…...

常见的api:Runtime Object
一.Runtiem的成员方法 1.getRuntime() 当前系统的运行环境 2.exit 停止虚拟机 3.avaliableProcessors 获取Cpu线程的参数 4.maxMemory JVM能从系统中获取总内存大小(单位byte) 5.totalMemory JVM已经从系统中获取总内大小(单位byte) 6.freeMemory JVM剩余内存大小(…...

Linux守护进程揭秘-无声无息运行在后台
在Linux系统中,有一些特殊的进程悄无声息地运行在后台,如同坚实的基石支撑着整个系统的运转。它们就是众所周知的守护进程(Daemon)。本文将为你揭开守护进程的神秘面纱,探讨它们的本质特征、创建过程,以及如何重定向它们的输入输出…...

python-Bert(谷歌非官方产品)模型基础笔记0.1.096
python-bert模型基础笔记0.1.015 TODOLIST官网中的微调样例代码Bert模型的微调限制Bert的适合的场景Bert多语言和中文模型Bert模型两大类官方建议模型Bert模型中名字的含义Bert模型包含的文件Bert系列模型参数介绍微调与迁移学习区别Bert微调的方式Pre-training和Fine-tuning区…...

Linux的命令补全脚本
一 linux命令补全脚本 Linux的命令补全脚本是一个强大且高效的工具,它能够极大地提高用户在命令行界面的工作效率。这种脚本通过自动完成部分输入的命令或参数,帮助用户减少敲击键盘的次数并降低出错率。接下来将深入探讨其工作原理、安装方式以及如何自…...

前端 JS 经典:打印对象的 bug
1. 问题 相信这个 console 打印语句的 bug,其实小伙伴们是遇到过的,就是你有一个对象,通过 console,打印一次,然后经过一些处理,再通过 console 打印,发现两次打印的结果是一样的,第…...

大型语言模型简介
大型语言模型简介 大型语言模型 (LLM) 是一种深度学习算法,可以使用非常大的数据集识别、总结、翻译、预测和生成内容。 文章目录 大型语言模型简介什么是大型语言模型?为什么大型语言模型很重要?什么是大型语言模型示例?大型语…...

javaWeb4 Maven
Maven-管理和构建java项目的工具 基于POM的概念 1.依赖管理:管理项目依赖的jar包 ,避免版本冲突 2.统一项目结构:比如统一eclipse IDEA等开发工具 3.项目构建:标准跨平台的自动化项目构建方式。有标准构建流程,能快速…...

eclipse连接后端mysql数据库并且查询
教学视频:https://www.bilibili.com/video/BV1mK4y157kE/?spm_id_from333.337.search-card.all.click&vd_source26e80390f500a7ceea611e29c7bcea38本人eclipse和up主不同的地方如下,右键项目名称->build path->configure build path->Libr…...

Windows mstsc
windows mstsc 局域网远程计算机192.168.0.113为例,远程控制命令mstsc...

百度/迅雷/夸克,网盘免费加速,已破!
哈喽,各位小伙伴们好,我是给大家带来各类黑科技与前沿资讯的小武。 之前给大家安利了百度网盘及迅雷的加速方法,详细方法及获取参考之前文章: 刚刚!度盘、某雷已破!速度50M/s! 本次主要介绍夸…...

SOA的参考架构
1. 以服务为中心的企业集成架构 IBM的Websphere业务集成参考架构(如图1所示,以下称参考架构)是典型的以服务为中心的企业集成架构。 图1 IBM WebSphere业务集成参考架构 以服务为中心的企业集成采用“关注点分离(Separation of Co…...

前端开发-表单和表格的区别
在前端开发中,表单(Form)和表格(Table)同样具有不同的用途和结构: 前端表单(Form): 数据收集:表单用于收集用户输入的数据,如文本输入、选择选项等。用户交…...

Data Management Controls
Data Browsing and Analysis Data Grid 以标准表格或其他视图格式(例如,带状网格、卡片、瓷砖)显示数据。Vertical Grid 以表格形式显示数据,数据字段显示为行,记录显示为列。Pivot Grid 模拟微软Excel的枢轴表功…...

NextJs 数据篇 - 数据获取 | 缓存 | Server Actions
NextJs 数据篇 - 数据获取 | 缓存 | Server Actions 前言一. 数据获取 fetch1.1 缓存 caching① 服务端组件使用fetch② 路由处理器 GET 请求使用fetch 1.2 重新验证 revalidating① 基于时间的重新验证② 按需重新验证revalidatePathrevalidateTag 1.3 缓存的退出方式 二. Ser…...

腾讯开源人像照片生成视频模型V-Express
网址 https://github.com/tencent-ailab/V-Express 下面是github里的翻译: 在人像视频生成领域,使用单张图像生成人像视频变得越来越普遍。一种常见的方法是利用生成模型来增强受控发电的适配器。 但是,控制信号的强度可能会有所不同&…...

pytorch使用DataParallel并行化保存和加载模型(单卡、多卡各种情况讲解)
话不多说,直接进入正题。 !!!不过要注意一点,本文保存模型采用的都是只保存模型参数的情况,而不是保存整个模型的情况。一定要看清楚再用啊! 1 单卡训练,单卡加载 #保存模型 torc…...

PS初级|写在纸上的字怎么抠成透明背景?
前言 上一次咱们讲了很多很多很多的抠图教程,这次继续。。。最近有小伙伴问我:如果是写在纸上的字,要怎么把它抠成透明背景。 这个其实很简单,直接来说就是选择通道来抠。但有一点要注意的是,写在纸上的字࿰…...

Docker面试整理-Docker的网络是如何工作的?
Docker 的网络功能允许容器以多种方式连接到彼此、宿主机以及外部网络。Docker 使用不同的网络驱动来支持这些连接,每种驱动方式都适用于特定的用途。理解 Docker 的网络是如何工作的,可以帮助你更好地设计和管理容器化应用的通信。 Docker 网络驱动 bridge:默认网络驱动。当…...

获得抖音商品评论 API 返回值
公共参数 名称类型必须描述keyString是调用key(获取key和密钥)secretString是调用密钥api_nameString是API接口名称(包括在请求地址中)[item_search,item_get,item_search_shop等]cacheString否[yes,no]默认yes&am…...

Qt | QtBluetooth(蓝牙电脑当服务端+手机当客户端) 配对成功啦
01、前言 没有演示,因为穷,电脑没有带蓝牙,但是已在其他电脑进行演示,可以满足配对,后期再补充和手机进行聊天,如果有聊天的记得私聊我,好处大大滴。02、QtBlueTooth 简介 QtBluetooth 是一个跨平台的蓝牙库,它允许开发者创建在支持蓝牙的设备上运行的应用程序。这个库…...

我找到了全网最低价买服务器的 bug !!!
拍断大腿 周五,放松一下,给大家分享下我最近的事儿,以及带大家薅个(可能会有)的羊毛。 上个月,家里买了 Apple TV(可理解为苹果的电视盒子)装了 infuse(一个在电视盒子上…...

聚类的外部指标(Purity, ARI, NMI, ACC) 和内部指标(NCC,Entropy,Compactness,Silhouette Index)
在聚类分析中,外部指标和内部指标用于评估聚类结果的质量。外部指标需要知道真实的类别标签,而内部指标则仅基于聚类结果本身进行评估。 外部指标 Purity (纯度): 计算聚类结果中每个簇中最多数目的样本所属的类别,并计算所有簇的该类别样本数之和占所有样本数的比例。 Pyt…...

国标GB/T 28181详解:国标GBT28181-2022的客户端主动发起历史视音频回放流程
目录 一、定义 二、作用 1、提供有效的数据回顾机制 2、增强监控系统的功能性 3、保障数据传输与存储的可靠性 4、实现精细化的操作与控制 5、促进监控系统的集成与发展 三、历史视音频回放的基本要求 四、命令流程 1、流程图 2、流程描述 五、协议接口 1、会话控…...

Vue项目安装axios报错npm error code ERESOLVE npm error ERESOLVE could not resolve解决方法
在Vue项目中安装axios时报错 解决方法:在npm命令后面加--legacy-peer-deps 例如:npm install axios --save --legacy-peer-deps 因为别的需求我把node版本重装到了最新版(不知道是不是这个原因),后来在项目中安装axi…...

【Linux】Centos7升级内核的方法:yum更新(ELRepo)
😎 作者介绍:我是程序员洲洲,一个热爱写作的非著名程序员。CSDN全栈优质领域创作者、华为云博客社区云享专家、阿里云博客社区专家博主。 🤓 同时欢迎大家关注其他专栏,我将分享Web前后端开发、人工智能、机器学习、深…...

【CSS】object-fit 和 object-position 属性详解
目录 object-fit属性属性值:使用场景: object-position 属性语法:例如:使用场景: object-fit和object-position是CSS属性,用于控制图像或视频在其容器中的适应和定位方式。 object-fit属性 属性值…...

【算法专题--栈】最小栈--高频面试题(图文详解,小白一看就会!!)
目录 一、前言 二、题目描述 三、解题方法 ⭐解题方法--1 ⭐解题方法--2 四、总结 五、共勉 一、前言 最小栈这道题,可以说是--栈专题--,比较经典的一道题,也是在面试中频率较高的一道题目,通常在面试中,面试官可…...

Vite项目构建chrome extension,实现多入口
本项目使用Vite5 Vue3进行构建。 要使用vite工程构建浏览器插件,无非就是要实现popup页面和options页面。这就需要在项目中用到多入口打包(生成多个html文件)。 实现思路: 通过配置vite工程,使得项目打包后有两个h…...

【vector模拟实现】附加代码讲解
vector模拟实现 一、看源代码简单实现1. push_backcapacity(容量)sizereserve(扩容)operator[ ] (元素访问) 2. pop_back3. itorator(迭代器)4.insert & erase (头插…...