JEditableTable help document

Parameter configuration

parameter type mandatory instructions
columns array ✔ ️ The following table describes the configuration of the table columns
dataSource array ✔ ️ Tabular data
loading boolean Whether it is loading. No rows will be displayed during loading. Default is false
actionButton boolean Whether to display action buttons, including “Add” and “delete”. The default value is false
rowNumber boolean Whether to display line numbers. Default is false
rowSelection boolean Whether rows are selectable. Default is false
dragSort boolean Draggable or not. Default is false
dragSortKey string Drag the sorted store Key to get the value on getValues() without having it defined in columns. The default is orderNum
maxHeight number Set the maximum height (PX), default 400
disabledRows object Disable lines. The disabled lines cannot be selected or edited. For details, see an example
disabled boolean Whether to disable all rows. Default is false

Columns Description of parameters

parameter type mandatory instructions
title string ✔ ️ Table column header display problem
key string ✔ ️ The key corresponding to the column data in the data item must be unique
type string ✔ ️ The type of form that can be passedJEditableTableUtil.FormTypesThe assignment
width string The width of the column can be either a percentage orpxOr other units, percentages are recommended, and the width of each column should not add up to more than 100%, otherwise it may not achieve the desired effect. The percentage is automatically calculated if you leave it blank
placeholder string A prompt for the expected value of the form can be usedThe ${... }Variable replacement text (see detailsThe ${... } how variables are used)
defaultValue string The default value takes effect when a row is added
validateRules array Form authentication rules, for details about how to configure themValidateRules Configuration rules
props object Set custom attributes added to form elements, for example:props:{title: 'show title'}
disabled boolean Whether to disable the current column. Default is false
Parameter required when type=checkbox
parameter type mandatory instructions
defaultChecked boolean Default value Whether to select
customValue array For custom values, checkbox requires Boolean values if the data is other values (e.g'Y' or 'N'), will cause an error, so this attribute is provided for conversion, for example:customValue: ['Y','N']Will,trueconvert'Y'.falseconvert'N'And vice versa
Parameter required when type=select
parameter type mandatory instructions
options array ✔ ️ For the drop-down list, see the following table
allowInput boolean Whether to allow users to enter content and create new content
dictCode String Data dictionary Code, concatenated after options if options also has a value

Options Required parameters

parameter type mandatory instructions
text string ✔ ️ Show the title
value string ✔ ️ The real value
title string Display title (deprecated, text is preferred if both title and text are filled in)
Parameter required when type=upload
parameter type mandatory instructions
action string ✔ ️ Path to upload files
token boolean Whether to transfer the token during the upload
responseName string ✔ ️ To retrieve the returned file name from Response after successful upload, fill in the name of the field containing the file name returned by the background
Parameter required when type=slot
parameter type mandatory instructions
slotName string ✔ ️ The name of the slot.

ValidateRules Configuration rules

What validateRules require is an array of rules, each of which is a rule of type Object, with the following parameters

  • requiredMandatory or not, optional value istrueorfalse
  • patternRegular expression verification. The verification succeeds only when the value of the regular expression is successfully matched
  • handlerFor details about how to use custom function verification, seeThe sample of five
  • messagePrompt text that is displayed when validation failsThe ${... }Variable replacement text (see detailsThe ${... } how variables are used)
  • For example, see Example 2

The event

The event name trigger parameter
added Triggered when the add row operation is complete
deleted Triggered when row deletion is complete (batch deletion is triggered only once) deleteIdsId that is logically deleted
selectRowChange Triggered when a row is selected or deselected selectedRowIdsId of the selected row
valueChange An event that is triggered when data changes { type, row, column, value, target }The Event object

methods

For how to call a method, please check how to call a method in the FAQ

initialize

Used to initialize the table (empty the table)

  • Parameters:
  • The return value:
resetScrollTop

Reset the scrollbar Top position

  • Parameters:
Parameter names type mandatory instructions
top number New top position, empty to scroll to the last recorded position, used to solve the problem of switching the TAB TAB when the white screen and automatically scroll bar to the top
  • The return value:
add

By default, when the user’s scroll bar is already at the bottom, the scroll bar will be fixed at the bottom, that is, after the addition, the user does not need to manually scroll, but will automatically scroll to the bottom

  • Parameters:
Parameter names type mandatory instructions
num number Add a few lines, default is 1
forceScrollToBottom boolean Does it force the user’s scroll bar to scroll to the bottom regardless of where it is after being added, default is false
  • The return value:
removeRows

Delete one or more rows actively

  • Parameters:
Parameter names type mandatory instructions
id A string or an array ✔ ️ Id of the deleted row. If you want to delete one ID, you can pass in the ID directly. If you want to delete multiple ids, you need to pass in the id as an array
  • The return value:
removeSelectedRows

Actively delete the selected row

  • Parameters:
  • The return value:
getValues

Used to get the values of all forms in the table for form validation

  • Parameters:
Parameter names type mandatory instructions
callback function ✔ ️ The callback method that gets the value is passed inerrorandvaluesTwo parameters.error: Number of failed validations, when equal to0“Means verification passed;values: The value obtained (this field has data even if it fails validation)
validate boolean Whether to perform form authentication. The default istrue, is set tofalseIndicates that form validation is ignored
rowIds array By default, all rows are returned, if passed inrowIds, then only and will be returnedrowIdsIf there is no matching data, an empty array is returned
  • The return value:
getValuesSync

A synchronized version of getValues, which returns the retrieved data directly

  • Parameters:
Parameter names type mandatory instructions
options object Options, see required parameters below
    • optionsThe required parameters
Parameter names type mandatory instructions
validate boolean Whether to perform form authentication. The default istrue, is set tofalseIndicates that form validation is ignored
rowIds array By default, all rows are returned, if passed inrowIds, then only and will be returnedrowIdsIf there is no matching data, an empty array is returned
  • Return value: object

    • errorThe number of failed verifications when equal to0“Indicates that the authentication is successful
    • valuesValue obtained (this field has data even if it fails validation)
  • Use the sample

let { error, values } = this.$refs.editableTable.getValuesSync({ validate: true.rowIds: ['rowId1'.'rowId2']})if (error === 0) {
    console.log('Form verified, data:', values);
} else {
    console.log('Failed form validation, data:', values);
}
Copy the code
getValuesPromise

The promise version of getValues passes the received value in resolve and the cause of failure in reject, such as VALIDATE_NO_PASSED

  • Parameters:
Parameter names type mandatory instructions
validate boolean withgetValuesthevalidateparameter
rowIds array By default, all rows are returned, if passed inrowIds, then only and will be returnedrowIdsIf there is no matching data, an empty array is returned
  • The return value: Promise
getDeleteIds

Gets the id of the row to be logically deleted and returns an array that the user can pass into the background and delete in batches

  • Parameters:
  • The return value: array
getAll

All values, including values and deleteIds, are passed in resolve: {values, deleteIds} is passed in reject, for example, VALIDATE_NO_PASSED

  • Parameters:
Parameter names type mandatory instructions
validate boolean withgetValuesthevalidateparameter
  • The return value: Promise
setValues

Actively set values for rows and columns in the table

  • Parameters:
Parameter names type mandatory instructions
values array Pass in an array where each entry is a new row of values, as shown in the example below
  • The return value:
  • Example:
setValues([
    {
        rowKey: id1, / / the id
        values: { // In this case the name of values is the key configured in your columns
            'name': 'zhangsan'.'age': '20'}}, {rowKey: id2,
        values: {
            'name': 'lisi'.'age': '23'}}])Copy the code
clearSelection

Actively empty the selected rows

  • Parameters:
  • The return value:

A built-in slot

Slot, instructions
buttonBefore On the operation buttonIn front of theInsert the slot without receivingactionButtonInfluence of attributes
buttonAfter On the operation buttonbehindInsert the slot without receivingactionButtonInfluence of attributes

The ${… } how variables are used

In placeholder and message, you can use ${… } variable to replace text. In example 2, the title column is configured with the name, and the placeholder placeholder is configured with please type in ${title}, so it will end up with please type in the name. That’s ${… ${} ${title, key, defaultValue


JEditableTableUtil instruction

The JEditableTableUtil utility class was mentioned earlier when columns were configured, so if you want detailed instructions, see here

The export of constants

FormTypes

This is the constant value used when configuring columns. Type, including

  • normalBy default, values are displayed directly without rendering the form
  • inputDisplay input field
  • inputNumberDisplays the numeric input box
  • checkboxDisplay multiple boxes
  • selectDisplay selector (drop-down box)
  • dateDate picker
  • datetimeDate and time picker
  • uploadUpload Component (file domain)
  • slotCustom slot

VALIDATE_NO_PASSED

In judging whether the form validation through use, if reject the value of the = = = VALIDATE_NO_PASSED represents form validation failed, you can do the corresponding other processing, the opposite may be an error happened, you can use the console. The error output

Method of encapsulation

validateTables

When you have multiple instances of JEditableTable on your page, getting the value of each instance and determining whether the form validates or not can be extremely tedious, so we’ve wrapped that up into a function that you can call. It can fetch and validate the values of multiple JEditableTable instances at the same time, and will only return the values if all instances of the form have passed validation, otherwise it will tell you which instance did not pass validation. See the following example for details

  • Parameters:
Parameter names type mandatory instructions
cases array Pass in an array where each entry is an instance of JEditableTable
  • The return value: Promise
  • Example:
import { validateTables, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
/ / packaging cases
let cases = []
cases.push(this.$refs.editableTable1)
cases.push(this.$refs.editableTable2)
cases.push(this.$refs.editableTable3)
cases.push(this.$refs.editableTable4)
cases.push(this.$refs.editableTable5)
// Validate and get the values of multiple instances simultaneously
validateTables(cases).then((all) = > {
    // All is an array, each of which corresponds to the subscript of the cases passed in, including values and deleteIds
    console.log('All instance values:', all)
}).catch((e = {}) = > {
    // Determine whether the form validation failed
    if (e.error === VALIDATE_NO_PASSED) {
        console.log('Failed instance subscript :', e.index)
    } else {
        console.error('Exception occurred :', e)
    }
})
Copy the code

FAQ

How is the method called?

In example 1, we set a ref=”editableTable” attribute, so we can use this.$refs.editableTable in vUE to get the instance of the table and call its methods. If I want to obtain the initialize method, it can be so write: enclosing $refs. EditableTable. The initialize ()

How do I get the value of the form?

Get it using the getValue method, as shown in Example 3

How do I do form validation?

Form validation is performed by default when fetching a value, and the user validates the form being entered when typing, as long as the rules are configured

How do I add or remove a line?

This functionality is packaged into the component, so you can simply set actionButton to True, or you can call new methods or changes in the code, as described above.

Why does switching tabs with the ATab component result in a blank screen or zero scrollbar position?

In the ATab component, the position of the scroll bar will be zero, and the onScroll method will not be triggered, so the row cannot be dynamically loaded, leading to the problem of white screen. ResetScrollTop () does not trigger the onChange event if the ATab component’s activeKey is changed.

  • The sample
<template>
    <a-tabs @change="handleChangeTab">
        <a-tab-pane tab="Table 1" :forceRender="true" key="1">
            <j-editable-table
                ref="editableTable1"
                :loading="tab1.loading"
                :columns="tab1.columns"
                :dataSource="tab1.dataSource"/>
        </a-tab-pane>
        <a-tab-pane tab="Table 2" :forceRender="true" key="2">
            <j-editable-table
                ref="editableTable2"
                :loading="tab2.loading"
                :columns="tab2.columns"
                :dataSource="tab2.dataSource"/>
        </a-tab-pane>
    </a-tabs>
</template>
Copy the code
/* ignore some code snippets --*/
methods: {

      /** Resets the scroll bar state of the editableTable while toggling the TAB */
      handleChangeTab(key) {
        this.$refs[`editableTable${key}`].resetScrollTop()
      }

}
/* ignore some code snippets --*/
Copy the code

How to use slot(custom slot)?

See example 4 (slot) for a code example.


The sample a

<j-editable-table
    ref="editableTable"
    :loading="loading"
    :columns="columns"
    :dataSource="dataSource"
    :rowNumber="true"
    :rowSelection="true"
    :actionButton="true"
    style="margin-top: 8px;"
    @selectRowChange="handleSelectRowChange"/>
Copy the code

Example 2


import { FormTypes } from '@/utils/JEditableTableUtil'

/* ignore some code snippets --*/
columns: [{title: 'name'.key: 'name'.type: FormTypes.input,
        placeholder: 'Please enter ${title}'.defaultValue: 'said the name'.// Form validation rules
        validateRules: [{required: true./ / required
                message: '${title} cannot be empty ' // The text of the prompt
            },
            {
                pattern: /^[a-z|A-Z][a-z|A-Z\d_-]{0,}$/./ / regular
                message: ${title} must start with a letter and may contain digits, underscores, or dashes.}]}, {title: 'age'.key: 'age'.type: FormTypes.inputNumber,
        placeholder: 'Please enter ${title}'.defaultValue: 18.validateRules: [{required: true.message: '${title} cannot be empty '}}]]/* ignore some code snippets --*/
Copy the code

Example 3

// Get the id of the field to be logically deleted
let deleteIds = this.$refs.editableTable.getDeleteIds();
// Get the values of all forms and validate
this.$refs.editableTable.getValues((error, values) = > {
    // If the number of errors is 0, the authentication is successful
    if (error === 0) {
        this.$message.success('Verified')
        // Commit the passed array to the background or do other processing on your own
        console.log(deleteIds, values)
    } else {
        this.$message.error('Verification failed')}})Copy the code

Example 4 (slot)

<template>
    <j-editable-table :columns="columns" :dataSource="dataSource">
        <! -- Define slot -->
        <! That define the slot method has been recommended to the vue new method named slot (https://cn.vuejs.org/v2/guide/components-slots.html#), the old version has been abandoned writing no longer support - >
        <! - if webstorm writes an error, please see this article: https://blog.csdn.net/lxq_9532/article/details/81870651 - >
        <template v-slot:action="props">
            <a @click="handleDelete(props)">delete</a>
        </template>
    </j-editable-table>
</template>
<script>
    import { FormTypes } from '@/utils/JEditableTableUtil'
    import JEditableTable from '@/components/jeecg/JEditableTable'
    export default {
        components: { JEditableTable },
        data() {
            return {
                columns: [
                    // ...
                    {
                        title: 'operation'.key: 'action'.width: '8%'.type: FormTypes.slot, // Define the column as a custom interpolation column
                        slotName: 'action' // Slot name, corresponding to the content after the colon and before the equal sign of v-slot}}},methods: {
            /* a TAB click event to remove the currently selected line */
            handleDelete(props) {
                // Parameter description
                // props. Index: subscript of the current line
                // props. Text: the current value, either defined by defaultValue or retrieved from the dataSource
                // props. RowId: id of the currently selected row, or temporary ID if it is a new row
                // props. Column: the column for the current operation
                // props. GetValue: This is a function that gets all the values of the current line (do not use this in template).
                // example: const value = props. GetValue ()
                // props. Target: the instance that triggered the current event, and the method in that instance can be called directly (do not use in template)
                / / example: target. The add ()

                // Delete the current row
                let { rowId, target } = props
                target.removeRows(rowId)
            }
        }
    }
</script>
Copy the code

The sample of five

// This example is a custom function validation
columns: [{title: 'Field name'.key: 'dbFieldName'.type: FormTypes.input,
        defaultValue: ' '.validateRules: [{// Custom function validation handler
                handler(type, value, row, column, callback, target) {
                    // type Specifies the type of verification triggered (input, change, blur).
                    // value Specifies the current verification value
                    // The callback(flag, message) method must be executed only once
                    // flag = Indicates whether the check is passed. If this parameter is not specified or null is specified, no operation is performed
                    // message = The type of the prompt. The configured message is used by default
                    // target instance object for row editing

                    if (type === 'blur') {

                        if (value === 'abc') {
                            callback(false.'${title} cannot be ABC ') // false = failed, can follow the custom prompt
                            return
                        }

                        let { values } = target.getValuesSync({ validate: false })
                        let count = 0
                        for (let val of values) {
                            if (val['dbFieldName'] === value) {
                                if (++count >= 2) {
                                    callback(false.'${title} cannot be repeated ')
                                    return
                                }
                            }
                        }
                        callback(true) // true = Pass validation
                    } else {
                        callback() // If no operation is performed or null is specified, no operation is performed}},message: '${title} Default prompt '}}],]Copy the code