When doing the background system, it is estimated that the most contact is the form + form, so as to increase, delete, change and check the operation.
This article, efforts to add, delete, change and check the general logic analysis of the removal, use, can be through a simple configuration, on a complex page.
If you can, you can read the preparation first:
- Make el-Form more useful by configuring it
- Make el-table easier to use by configuring it
This code, involving more files, want to see details, you can refer to Github
TL; DR
- Basic query and table display
- Tables are paginated and sorted
- To change the query criteria, you need to reset the page number and sort the query
- Resetting query criteria
- Add new table entry
- Edit table entry
1. Basic queries and forms
The first step is to display the form. The data of the form is also displayed by requesting the data.
We’ve wrapped tables and form plug-ins before.
A page, let’s look at the query criteria, turn it into a model for a form, and the form is much simpler, and configure the columns.
Of course, the query condition, in addition to the form, also plus the next page and sort data, pageIndex pageSize sortBy isAsc.
The first version of the display effect:
The first version of the core code, detailed code at the end of the article:
You can switch between c1 branches on Github
2. Sorting and paging
In order:
- Direct configuration without paging
colConfig
thesortable:true
Is displayed in the header of the columnSorting symbol
the - Paging, if you need to request data, configure
colConfig
thesortable:custom
, write on the component@sort-change="sortChange"
When the sort symbol is clicked, it is triggeredsort-change
Events.
If the page number changes: The page component has the event current-change, set pageIndex accordingly
Monitor pageIndex sortBy isAsc changes when requesting table data
C2 branches can be switched on Github
3. Modify the search conditions
Click query, according to the query conditions, request data.
!!!!!!!!! Note that the current page count needs to be reset to 1.
The C3 branch can be switched on Github
4. Reset
Resetting actually has three aspects:
- Reset query form: Resets all field values to their original values and removes validation results
- Reset current page: Set to 1
- Reset sort: Resets the sort to the default
!!!!!!!!! Note that in addition to isAsc and sortBy in data, the sorting icon in the table needs to be correct.
There are two ways to set the sort icon:
- ClearSort: Used to clear the sorting criteria and restore the data to the unsorted state
- Sort: Sorts tables manually. The prop property specifies the order and order specifies the sort order.
Therefore, isAsc and sortBy in data under Watch are required to display corresponding sorting ICONS when changes occur.
To facilitate monitoring, place isAsc and sortBy in one object so that you only need to listen once
clickResetBtn() {
// Reset the query form to reset all field values to their original values and remove the validation result
this.$refs.queryForm.resetFields();
// Reset the page count
this.pageIndex = 1;
// Reset the sort
this.sortConfig = { ... this.sortConfigDefault }; },Copy the code
Effect:Code:
You can switch c4 branches on Github
5. New
The new function will be displayed in a pop-up box. After filling in the form and confirming, it will be displayed in the list.
In code:
DOM
Prepare pop-ups and forms in advance, but don’t display them- After clicking New, the pop-up box is displayed
- Click “Submit” in the pop-up box, there is an error message error, yes request new interface
- Look at the requirements at this point, but most need to reset the page and request the list data again to display the information you just created
- Details: You need to reset the popup form because the same form may have residual validation when you click New the second time
Effect:
Code:
DOM core code:
el-dialog(:title="dialogFormTitle" :visible.sync="isShowDialogForm" center width="340px") enhanced-el-form(ref="dialogForm" :model="dialogFormModel" :schema="dialogFormSchema" label-width="70px" label-position= "right") template(#footer) el-form-item el-button.btn(type='primary', @click='clickCancelOfDialogForm') cancel el-button. BTN (plain, @click='clickConfirmOfDialogForm') confirmCopy the code
You can switch c5 branches on Github
6. Edit
The edit function is usually the same form box as the new one. But unlike creating a new form, editing a form has data.
In code:
DOM
Prepare pop-ups and forms in advance, but don’t display them- Table configuration plus editing
- After clicking Edit, fill in the form data and display the popbox
- Click submit in the pop-up box, there is an error prompt error, yes request edit interface
- Look at the requirements at this point, but most need to update the data in the current row
Effect:
Code:
Colconfigs.js adds an action column:
{ prop: "score".label: "Score".sortable: "custom" },
{ slotName: "action".label: "Operation" }
Copy the code
You can switch c6 branches on Github
7. To be continued
For time reasons, I’ll write it here. End goal: package into components, efficient use ~
code
Code: 1. Display query forms and tables
Here the project is created using vue Create.
The overall code is slightly more complex, with mock data, requests, and $API globally.
There are many files: but with the exception of the app. vue file, the rest of the files are left untouched.
In this way, files in red boxes are files that need to be moved
App.vue
App.vue
<template lang="pug"> div#app //- form area enhanced el-form(ref="queryForm" :model="model" :schema="schema" :inline="true") label-width="100px" label-position= "right") template(#footer) el-form-item.app-btns-box el-button.btn(type='primary', @click='clickSearchBtn') query // enhanced el-table(:data='tableData', :col-configs='colConfigs') template(#name="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") a.link(href="javascript:;" @click="clickName(row)") {{row.name}} //- pagination-box el-pagination(@current-change='changeTablePage', :current-page.sync='pageIndex', :page-size='pageSize', layout='prev, pager, next, jumper', :total='dataCount') </template> <script> import EnhancedElTable from "@/components/EnhancedElTable"; import EnhancedElForm from "@/components/EnhancedElForm"; import schema from "./schema"; import colConfigs from "./colConfigs"; export default { name: "app", components: { EnhancedElTable, EnhancedElForm }, data() { return { model: {}, // form configuration schema, // table configuration colConfigs, // table request raw data tableData: [], // have data means that it is possible to page pageIndex: 0, pageSize: 10, isAsc: "", sortBy: "", // Total data length, basically only for the paging component dataCount: 0}; }, mounted() { this.getTableData(); }, methods: { async getTableData() { const { pageIndex, pageSize, sortBy, isAsc } = this; let params = { ... this.model, pageIndex, pageSize, sortBy, isAsc }; const res = await this.$api.ApiGetList(params); this.tableData = res.data; this.dataCount = res.dataCount; }, clickName() {}, clickSearchBtn() {}, changeTablePage(curPageIndex) { this.pageIndex = curPageIndex; }}}; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } .el-table { border: 1px solid #e8e8e8; width: 90%; margin: auto; } .pagination-box { margin-top: 20px; text-align: center; } </style>Copy the code
Form and table configuration: colconfig.js, schema.js
colConfig.js
export default[{prop: "orderNumber".label: "Serial number" },
{
slotName: "name".label: "Name"
},
{
prop: "year".label: "Year"
},
{
prop: "quarter".label: "Quarter"
},
{ prop: "score".label: "Score".sortable: "custom"}];Copy the code
schema.js
export default[{modelKey: "year".label: "Year".type: "date-picker".props: {
type: "year".format: "yyyy".valueFormat: "yyyy".style: { width: "150px"}}}, {modelKey: "quarter".label: "Quarter".type: "select".props: {
options: [{value: "Spring".label: "Spring" },
{ value: "Summer".label: "Summer" },
{ value: "Autumn".label: "Autumn" },
{ value: "Winter".label: "Winter"}].style: { width: "150px"}}}, {modelKey: "name".label: "Name".type: "input".style: { width: "150px"}}];Copy the code
Two components: enhancedeltable. vue and enhancedelform. vue
EnhancedElTable.vue
<template lang="pug"> el-table(ref="elTable" :data="data" v-bind="$attrs" v-on="$listeners") template(v-for="colConfig in colConfigs") slot(v-if="colConfig.slotName" :name="colConfig.slotName" v-bind="colConfig") el-table-column(v-else v-bind="colConfig" :key="colConfig.prop") </template> <script> export default { name: "enhanced-el-table", props: { data: { type: Array, default() { return []; } }, colConfigs: { type: Array, default() { return []; } } }, mounted() { console.log(444, this.tableData); const methods = [ "clearSelection", "toggleRowSelection", "toggleAllSelection", "toggleRowExpansion", "setCurrentRow", "clearSort", "clearFilter", "doLayout", "sort" ]; methods.forEach(method => (this[method] = this.$refs.elTable[method])); }}; </script>Copy the code
EnhancedElForm.vue
<template lang="pug"> el-form(ref="elForm" :model="model" :rules="rules" v-bind="$attrs" v-on="$listeners") slot(name="header") template(v-for="config in schema" ) slot(v-if="config.slotName" :name="config.slotName" v-bind="config") el-form-item(v-else :label="config.label" :prop="config.modelKey" :key="config.modelKey") el-radio-group(v-if="config.type==='radio-group'" v-model="model[config.modelKey]" v-bind="config.props") el-radio(v-for="(item,index) in config.props.options" :key="index" :label="typeof item==='object'? item.value:item") {{ typeof item==='object'? item.label:item }} el-checkbox-group(v-else-if="config.type==='checkbox-group'" v-model="model[config.modelKey]" v-bind="config.props") el-checkbox(v-for="(item,index) in config.props.options" :key="index" :label="typeof item==='object'? item.value:item") {{ typeof item==='object'? item.label:item }} el-select(v-else-if="config.type==='select'" v-model="model[config.modelKey]" v-bind="config.props") el-option(v-for="(item,index) in config.props.options" :key="index" :value="typeof item==='object'? item.value:item" :label="typeof item==='object'? item.label:item") component(v-else :is="'el-'+config.type" v-model="model[config.modelKey]" v-bind="config.props") {{config.text}} slot(name="footer") </template> <script> export default { name: "enhanced-el-form", props: { model: { type: Object, default() { return {}; } }, schema: { type: Array, default() { return {}; } } }, computed: { rules() { return this.schema.reduce((acc, cur) => { acc[cur.modelKey] = cur.rules; // Date component may have children const hasChildren = cur.children && cur.children. Length; hasChildren && cur.children.forEach(child => (acc[child.modelKey] = child.rules)); return acc; }, {}); } // return const method = ["validate", "validateField", "resetFields", "clearValidate"]; // return const method = ["validate", "validate", "resetFields", "clearValidate"]; methods.forEach(method => (this[method] = this.$refs.elForm[method])); }}; </script>Copy the code
Mock data section:.env.mock, mock. Js, vue.config.js
.env.mock
NODE_ENV = 'mock'
Copy the code
mock.js
module.exports = Array.from({ length: 28 }, (v, i) = > ({
orderNumber: i + 1.year: "199" + i - 0 + 1 + "".quarter: i % 4= = =1 ? "Spring" : i % 4= = =2 ? "Summer" : i % 4= = =3 ? "Autumn" : "Winter".name: Li three `${i + 1}`.score: 8 `${i}`
}));
Copy the code
vue.config.js
const nativeData = require("./mock");
module.exports = {
devServer: {
before(app) {
app.get("/api/list".(req, res) = > {
console.log(req.query);
const { pageIndex, pageSize, sortBy, isAsc, year, quarter, name } = req.query;
let data = [...nativeData];
// get the query condition
const conditions = { year, quarter, name };
// check whether the query condition has a value
const keysOfHasValue = Object.keys(conditions).filter(
key= > conditions[key]
);
const isHasCondition = keysOfHasValue.length > 0;
// If there are query conditions, filter them
if (isHasCondition) {
data = data.filter(item= >
keysOfHasValue.every(key= > item[key] === conditions[key])
);
}
// If there is a sort
if (sortBy && isAsc) {
isAsc === "true"
? data.sort((x, y) = > x[sortBy] - y[sortBy])
: data.sort((x, y) = > y[sortBy] - x[sortBy]);
}
// If there is paging
if (pageSize) {
data = data.slice((pageIndex - 1) * pageSize, pageSize * pageIndex);
}
return res.json({
state: 1,
data,
dataCount: data.length }); }); }}};Copy the code
Added request: API /index.js
api/index.js
import axios from "axios";
// All requests are configured uniformly
const instance = axios.create({ timeout: 5000 });
// Request interceptor, add appID, sign, etc
instance.interceptors.request.use(
config= > {
config.method === "get" && (config.params.appid = "Yan sauce");
return config;
},
error= > Promise.error(error)
);
// Response interceptor, unified handling of errors
instance.interceptors.response.use(
// The request succeeded
res= > {
// 200 indicates that the request was successful
const isSuccess = res.status === 200;
if(! isSuccess) {Promise.reject(res);
return;
}
return Promise.resolve(res.data);
},
// The request failed
error= > {
console.log(error);
if (!window.navigator.onLine) {
this.$message.error("Bad Internet");
return;
}
const { response } = error;
if (response) {
this.$message.error(response.message); }});export const ApiGetList = ({ pageIndex, pageSize, sortBy, isAsc, year, quarter, name }) = >
instance.get("/api/list", {
params: { pageIndex, pageSize, sortBy, isAsc, year, quarter, name }
});
Copy the code
Global API: main.js
main.js
import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import App from "./App.vue";
import * as api from "@/api";
// Make global access to the API easy
Vue.prototype.$api = api;
Vue.use(ElementUI);
new Vue({
el: "#app".render: h= > h(App)
});
Copy the code
Code: 2. Add sorting and page number changes
App.vue
<template lang="pug"> div#app //- form area enhanced el-form(:model="model" :schema="schema" :inline="true") label-width="100px" label-position= "right") template(#footer) el-form-item.app-btns-box el-button.btn(type='primary', @click='clickSearchBtn') enhanced-el-table(@sortchange ="sortChange" :data='tableData', :col-configs='colConfigs') template(#name="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") a.link(href="javascript:;" @click="clickName(row)") {{row.name}} //- pagination-box el-pagination(@current-change='changeCurrentPage', :current-page.sync='pageIndex', :page-size='pageSize', layout='prev, pager, next, jumper', :total='dataCount') </template> <script> import EnhancedElTable from "@/components/EnhancedElTable"; import EnhancedElForm from "@/components/EnhancedElForm"; import schema from "./schema"; import colConfigs from "./colConfigs"; Export default {name: "app", components: {EnhancedElTable, EnhancedElForm}, data() {return {// Form data: {}, // form configuration schema, // table configuration colConfigs, // table request raw data tableData: [], // have data means that it is possible to page pageIndex: 0, pageSize: 10, isAsc: "", sortBy: "", // Total data length, basically only for the paging component dataCount: 0}; }, mounted() { this.getTableData(); }, watch: { isAsc() { this.getTableData(); }, sortBy() { this.getTableData(); }, pageIndex() { this.getTableData(); } }, methods: { changeCurrentPage(curPageIndex) { this.pageIndex = curPageIndex; }, async getTableData() { const { pageIndex, pageSize, sortBy, isAsc } = this; let params = { ... this.model, pageIndex, pageSize, sortBy, isAsc }; const res = await this.$api.ApiGetList(params); this.tableData = res.data; this.dataCount = res.dataCount; }, sortChange({ column, prop, order }) { console.log(column, prop, order); this.isAsc = order === "ascending"; this.sortBy = prop; }, clickName() {}, clickSearchBtn() {} } }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } .el-table { border: 1px solid #e8e8e8; width: 90%; margin: auto; } .pagination-box { margin-top: 20px; text-align: center; } </style>Copy the code
Code: 3. Add query condition changes
App.vue
<template lang="pug"> div#app //- form area enhanced el-form(:model="model" :schema="schema" :inline="true") label-width="70px" label-position= "right") template(#footer) el-form-item.app-btns-box el-button.btn(type='primary', @click='clickSearchBtn') enhanced-el-table(@sortchange ="sortChange" :data='tableData', :col-configs='colConfigs') template(#name="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") a.link(href="javascript:;" @click="clickName(row)") {{row.name}} //- pagination-box el-pagination(@current-change='changeCurrentPage', :current-page.sync='pageIndex', :page-size='pageSize', layout='prev, pager, next, jumper', :total='dataCount') </template> <script> import EnhancedElTable from "@/components/EnhancedElTable"; import EnhancedElForm from "@/components/EnhancedElForm"; import schema from "./schema"; import colConfigs from "./colConfigs"; Export default {name: "app", components: {EnhancedElTable, EnhancedElForm}, data() {return {// Form data: {}, // form configuration schema, // table configuration colConfigs, // table request raw data tableData: [], // have data means that it is possible to page pageIndex: 0, pageSize: 10, isAsc: "", sortBy: "", // Total data length, basically only for the paging component dataCount: 0}; }, mounted() { this.sortConditionDefault = { isAsc: this.isAsc, sortBy: this.sortBy }; this.getTableData(); }, watch: { isAsc() { this.getTableData(); }, sortBy() { this.getTableData(); }, pageIndex() { this.getTableData(); } }, methods: { clickSearchBtn() { this.pageIndex = 1; this.sortBy = this.sortConditionDefault.sortBy; this.isAsc = this.sortConditionDefault.isAsc; this.getTableData(); }, changeCurrentPage(curPageIndex) { this.pageIndex = curPageIndex; }, async getTableData() { const { pageIndex, pageSize, sortBy, isAsc } = this; let params = { ... this.model, pageIndex, pageSize, sortBy, isAsc }; const res = await this.$api.ApiGetList(params); this.tableData = res.data; this.dataCount = res.dataCount; }, sortChange({ column, prop, order }) { console.log(column, prop, order); this.isAsc = order === "ascending"; this.sortBy = prop; }, clickName() {} } }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } .el-table { border: 1px solid #e8e8e8; width: 90%; margin: auto; } .pagination-box { margin-top: 20px; text-align: center; } </style>Copy the code
Code: 4. Add reset
App.vue
<template lang="pug"> div#app //- form area enhanced el-form(ref="queryForm" :model="model" :schema="schema" :inline="true") label-width="70px" label-position= "right") template(#footer) el-form-item.app-btns-box el-button.btn(type='primary', @ click = 'clickSearchBtn) query el - button. BTN (plain, // enhanced el-table(ref="mainTable" @sortchange ="sortChange" :data='tableData', :col-configs='colConfigs') template(#name="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") a.link(href="javascript:;" @click="clickName(row)") {{row.name}} //- pagination-box el-pagination(@current-change='changeCurrentPage', :current-page.sync='pageIndex', :page-size='pageSize', layout='prev, pager, next, jumper', :total='dataCount') </template> <script> import EnhancedElTable from "@/components/EnhancedElTable"; import EnhancedElForm from "@/components/EnhancedElForm"; import schema from "./schema"; import colConfigs from "./colConfigs"; Export default {name: "app", components: {EnhancedElTable, EnhancedElForm}, data() {return {// Form data: {quarter: ""}, // table configuration schema, // table configuration colConfigs, // table request raw data tableData: [], // have data means that the pageSize: 0, pageSize: SortConfig: {isAsc: "", sortBy: ""}, // dataCount: 0}; }, mounted() {this.sortConfigDefault = {... this.sortConfig }; this.getTableData(); }, watch: { sortConfig: { handler(newValue) { console.log(newValue); const order = newValue.isAsc === "" ? null : newValue.isAsc === false ? "descending" : "ascending"; const hasOrder = order ! == null; const mainTable = this.$refs.mainTable; // Set hasOrder if there is a sort, and clear hasOrder if there is no sort. mainTable.sort(newValue.sortBy, order) : mainTable.clearSort(); this.getTableData(); }, deep: true }, pageIndex() { this.getTableData(); }}, the methods: {clickResetBtn () {/ / reset query form, all the field values to reset to the initial value and remove check result this. $refs. QueryForm. ResetFields (); // set page count this.pageIndex = 1; // Reset sort this.sortconfig = {... this.sortConfigDefault }; }, clickSearchBtn() { this.pageIndex = 1; this.getTableData(); }, changeCurrentPage(curPageIndex) { this.pageIndex = curPageIndex; }, async getTableData() { const { pageIndex, pageSize } = this; let params = { ... this.model, ... this.sortConfig, pageIndex, pageSize }; const res = await this.$api.ApiGetList(params); this.tableData = res.data; this.dataCount = res.dataCount; }, sortChange({ column, prop, order }) { console.log(1, column, prop, order); this.sortConfig.isAsc = order === null ? "" : order === "ascending"; this.sortConfig.sortBy = prop; }, clickName() {} } }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } .el-table { border: 1px solid #e8e8e8; width: 90%; margin: auto; } .pagination-box { margin-top: 20px; text-align: center; } </style>Copy the code
5. Code: New
App.vue
<template lang="pug"> div#app //- form area enhanced el-form(ref="queryForm" :model="model" :schema="schema" :inline="true") label-width="70px" label-position= "right") template(#footer) el-form-item.app-btns-box el-button.btn(type='primary', @click='clickSearchBtn') query el-button. BTN (plain, @click='clickResetBtn') reset el-button. BTN (plain, @click='clickResetBtn') // enhanced el-table(ref="mainTable" @sortchange ="sortChange" :data='tableData', :col-configs='colConfigs') template(#name="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") a.link(href="javascript:;" @click="clickName(row)") {{row.name}} //- pagination-box el-pagination(@current-change='changeCurrentPage', :current-page.sync='pageIndex', :page-size='pageSize', layout='prev, pager, next, jumper', :total='dataCount') el-dialog(:title="dialogFormTitle" :visible.sync="isShowDialogForm" center width="340px") enhanced-el-form(ref="dialogForm" :model="dialogFormModel" :schema="dialogFormSchema" label-width="70px" label-position= "right") template(#footer) el-form-item el-button.btn(type='primary', @ click = 'clickCancelOfDialogForm) cancel el - button. BTN (plain, @ click = 'clickConfirmOfDialogForm) to determine < / template > < script > import EnhancedElTable from "@ / components/EnhancedElTable"; import EnhancedElForm from "@/components/EnhancedElForm"; import schema from "./schema"; import colConfigs from "./colConfigs"; Export default {name: "app", components: {EnhancedElTable, EnhancedElForm}, data() {return {// Form data: {}, // form configuration schema, // table configuration colConfigs, // table request raw data tableData: [], // have data means that it is possible to page pageIndex: 0, pageSize: SortConfig: {isAsc: "", sortBy: ""}, // dataCount: 0 False, dialogFormTitle: "Create student ", dialogFormModel: {}, dialogFormSchema: schema.map(item => {let res = {... item }; Res. rules = [{required: true, trigger: "blur", message: "cannot be null"}]; return res; })}; }, mounted() {this.sortConfigDefault = {... this.sortConfig }; this.getTableData(); }, watch: { sortConfig: { handler(newValue) { const order = newValue.isAsc === "" ? null : newValue.isAsc === false ? "descending" : "ascending"; const hasOrder = order ! == null; const mainTable = this.$refs.mainTable; // Set hasOrder if there is a sort, and clear hasOrder if there is no sort. mainTable.sort(newValue.sortBy, order) : mainTable.clearSort(); this.getTableData(); }, deep: true }, pageIndex() { this.getTableData(); } }, methods: { clickCreateBtn() { this.$refs.dialogForm && this.$refs.dialogForm.resetFields(); this.isShowDialogForm = true; }, clickCancelOfDialogForm() { this.isShowDialogForm = false; }, async clickConfirmOfDialogForm() { const isValid = await this.$refs.dialogForm.validate(); if (! isValid) { return; } // Since there is not much time to write more interfaces, // await this.$api.createData(this.dialogFormModel) // this.$message.success(' create success ~') this.isshowDialogForm = false; // Reset query criteria and sort this.resetQueryandsort (); }, resetQueryAndSort () {/ / reset query form, all the field values to reset to initial value and remove check result this. $refs. QueryForm. ResetFields (); // set page count this.pageIndex = 1; // Reset sort this.sortconfig = {... this.sortConfigDefault }; }, clickResetBtn() { this.resetQueryAndSort(); }, clickSearchBtn() { this.pageIndex = 1; this.getTableData(); }, changeCurrentPage(curPageIndex) { this.pageIndex = curPageIndex; }, async getTableData() { const { pageIndex, pageSize } = this; let params = { ... this.model, ... this.sortConfig, pageIndex, pageSize }; const res = await this.$api.ApiGetList(params); this.tableData = res.data; this.dataCount = res.dataCount; }, sortChange({ column, prop, order }) { console.log(1, column, prop, order); this.sortConfig.isAsc = order === null ? "" : order === "ascending"; this.sortConfig.sortBy = prop; }, clickName() {} } }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } .el-table { border: 1px solid #e8e8e8; width: 90%; margin: auto; } .pagination-box { margin-top: 20px; text-align: center; } </style>Copy the code
Code: Edit
App.vue
<template lang="pug"> div#app //- form area enhanced el-form(ref="queryForm" :model="model" :schema="schema" :inline="true") label-width="70px" label-position= "right") template(#footer) el-form-item.app-btns-box el-button.btn(type='primary', @click='clickSearchBtn') query el-button. BTN (plain, @click='clickResetBtn') reset el-button. BTN (plain, @click='clickResetBtn') // enhanced el-table(ref="mainTable" @sortchange ="sortChange" :data='tableData', :col-configs='colConfigs') template(#name="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") a.link(href="javascript:;" @click="clickName(row)") {{row.name}} template(#action="colConfig") el-table-column(v-bind="colConfig") template(#default="{row}") div(style="color:#409eff; Pagination -box el-pagination(@current-change='changeCurrentPage', :current-page.sync='pageIndex', :page-size='pageSize', layout='prev, pager, next, jumper', :total='dataCount') el-dialog(:title="dialogFormTitle" :visible.sync="isShowDialogForm" center width="340px") enhanced-el-form(ref="dialogForm" :model="dialogFormModel" :schema="dialogFormSchema" label-width="70px" label-position= "Right ") template(#footer) el-form-item el-button. BTN (plain,@click='clickCancelOfDialogForm') cancelled el-button.btn(type='primary', @ click = 'clickConfirmOfDialogForm) to determine < / template > < script > import EnhancedElTable from "@ / components/EnhancedElTable"; import EnhancedElForm from "@/components/EnhancedElForm"; import schema from "./schema"; import colConfigs from "./colConfigs"; Export default {name: "app", components: {EnhancedElTable, EnhancedElForm}, data() {return {// Form data: {}, // form configuration schema, // table configuration colConfigs, // table request raw data tableData: [], // have data means that it is possible to page pageIndex: 0, pageSize: SortConfig: {isAsc: "", sortBy: ""}, // dataCount: 0 False, dialogFormTitle: "Create student ", dialogFormModel: {}, dialogFormSchema: schema.map(item => {let res = {... item }; Res. rules = [{required: true, trigger: "blur", message: "cannot be null"}]; return res; })}; }, mounted() {this.sortConfigDefault = {... this.sortConfig }; this.getTableData(); }, watch: { sortConfig: { handler(newValue) { const order = newValue.isAsc === "" ? null : newValue.isAsc === false ? "descending" : "ascending"; const hasOrder = order ! == null; const mainTable = this.$refs.mainTable; // Set hasOrder if there is a sort, and clear hasOrder if there is no sort. mainTable.sort(newValue.sortBy, order) : mainTable.clearSort(); this.getTableData(); }, deep: true }, pageIndex() { this.getTableData(); }}, methods: {clickEdit(row) {this.isedit = true; // Note that this must be the first line down for later resetFields because the initial form value is empty when the page is first clicked to edit. If the bottom row is at the top and the page is edited and then new, resetFields will be disabled. NextTick also guarantees this function this.isShowDialogForm = true; this.$nextTick(() => { this.dialogFormModel = { ... row }; }); This.currow = row; this.currow = row; // This. DialogFormTitle = "modify "; }, async clickConfirmOfDialogForm() { const isValid = await this.$refs.dialogForm.validate(); if (! isValid) { return; } // Since there is not much time to write more interfaces, If (this.isedit) {// await this.$api.editData(this.dialogFormModel) this.$message. Success (" Modified successfully ~"); // Update the current row by traversing it Keys (this.dialogFormModel). ForEach (key => {this.currow [key] = this.dialogFormModel[key]; }); } else {// await this.$api.createData(this.dialogFormModel) this.$message. Success (" New message ~"); // Reset query criteria and sort this.resetQueryandsort (); } this.isShowDialogForm = false; }, clickCreateBtn() {this.isedit = false; This. DialogFormTitle = "New "; this.$refs.dialogForm && this.$refs.dialogForm.resetFields(); this.isShowDialogForm = true; }, clickCancelOfDialogForm() { this.isShowDialogForm = false; }, resetQueryAndSort () {/ / reset query form, all the field values to reset to initial value and remove check result this. $refs. QueryForm. ResetFields (); // set page count this.pageIndex = 1; // Reset sort this.sortconfig = {... this.sortConfigDefault }; }, clickResetBtn() { this.resetQueryAndSort(); }, clickSearchBtn() { this.pageIndex = 1; this.getTableData(); }, changeCurrentPage(curPageIndex) { this.pageIndex = curPageIndex; }, async getTableData() { const { pageIndex, pageSize } = this; let params = { ... this.model, ... this.sortConfig, pageIndex, pageSize }; const res = await this.$api.ApiGetList(params); this.tableData = res.data; this.dataCount = res.dataCount; }, sortChange({ column, prop, order }) { console.log(1, column, prop, order); this.sortConfig.isAsc = order === null ? "" : order === "ascending"; this.sortConfig.sortBy = prop; }, clickName() {} } }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } .el-table { border: 1px solid #e8e8e8; width: 90%; margin: auto; } .pagination-box { margin-top: 20px; text-align: center; } </style>Copy the code