Home  >  Article  >  Web Front-end  >  How to group and merge tables in Vue?

How to group and merge tables in Vue?

WBOY
WBOYOriginal
2023-06-25 16:38:571636browse

Vue is a popular JavaScript framework for building modern web applications. One common application scenario is data visualization, especially tables. When the amount of data is large, grouping and merging tables is very important to help users better understand and analyze the data. This article will introduce how to use Vue to implement the grouping and merging function of tables.

First, we need a table component. We can use Vue's built-in components f5d188ed2c074f8b944552db028f98a1, a34de1251f0d9fe1e645927f19a896e8, b6c5a531a458a2e790c1fd6421739d1c to create a basic table. In this table, we need to implement two types of rows: normal rows and summary rows. Normal rows are used to display data, while summary rows are used to display grouped totals.

Ordinary rows and summary rows can be distinguished by the structure of the data. Suppose we have an array containing student grades. Each element contains the student's name, age, gender, and grade. We can group this array by subject and calculate the total score for each group. This data structure can be expressed in the following form:

{
  'Math': {
    'totalCount': 100,
    'students': [
      { 'name': 'Alice', 'age': 18, 'gender': 'female', 'score': 90 },
      { 'name': 'Bob', 'age': 19, 'gender': 'male', 'score': 10 }
    ]
  },
  'English': {
    'totalCount': 80,
    'students': [
      { 'name': 'Charlie', 'age': 20, 'gender': 'male', 'score': 50 },
      { 'name': 'David', 'age': 21, 'gender': 'male', 'score': 30 }
    ]
  }
}

In this data structure, each key represents a subject and corresponds to an object containing student information. This object contains a totalCount property and a students array. The totalCount attribute represents the total score of this subject, and the students array represents the list of students in this subject.

After having this data structure, we can convert it into an array for display in the table. Each element of the array represents a row, which can be an ordinary row or a summary row. The normal row corresponds to each student in the student list for the subject, and the summary row corresponds to the total for the subject. This conversion process can be completed using a function:

function convertData(data) {
  const result = []
  for (const subject in data) {
    const subjectData = data[subject]
    result.push({
      'type': 'group',
      'subject': subject,
      'totalCount': subjectData.totalCount
    })
    for (const student of subjectData.students) {
      result.push({
        'type': 'item',
        'name': student.name,
        'age': student.age,
        'gender': student.gender,
        'score': student.score
      })
    }
  }
  return result
}

This function accepts a data object containing student scores and returns an array used to display the table. In this array, each element contains a type attribute and other column attributes. The type attribute indicates whether this element is a normal row or a summary row, the subject attribute indicates the subject name, the totalCount attribute indicates the total score of the subject, and other attributes indicate the name of the student , age, gender and grades.

After we have the data, we can start writing the table component. The table component should accept an array containing table data as input and render normal and summary rows based on the type property of the data.

First, we need to render the table header. The header should contain the titles of all columns. We can use an array to define the header column names and use the v-for binding to render each column's title separately.

<table>
  <thead>
    <tr>
      <th v-for="column in columns">{{ column }}</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(row, rowIndex) in rows" :key="rowIndex">
      <td v-for="(column, columnIndex) in columns" :key="columnIndex">
        <!-- 渲染单元格内容 -->
      </td>
    </tr>
  </tbody>
</table>

Next, we need to render the data rows. For ordinary rows, we need to render student information; for summary rows, we need to render subject names and total scores. We can use v-if to determine the type of the current row and render different content based on the type.

<table>
  <thead>
    <tr>
      <th v-for="column in columns">{{ column }}</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(row, rowIndex) in rows" :key="rowIndex">
      <td v-for="(column, columnIndex) in columns" :key="columnIndex">
        <template v-if="column === 'subject' && row.type === 'group'">{{ row[column] }}</template>
        <template v-else-if="row.type === 'item'">{{ row[column] }}</template>
        <template v-else-if="column === 'totalCount' && row.type === 'group'">{{ row[column] }}</template>
        <template v-else></template>
      </td>
    </tr>
  </tbody>
</table>

Finally, we need to convert the data array into the row and column format required by the table. We can use the computed attribute to monitor changes in input data and update the row and column format of the table when it changes.

computed: {
  columns() {
    const columns = ['name', 'age', 'gender', 'score']
    return ['subject', ...columns, 'totalCount']
  },
  rows() {
    const data = convertData(this.data)
    const rows = []
    let group = null
    for (const item of data) {
      if (item.type === 'group') {
        if (group) {
          rows.push(group)
        }
        group = {}
        for (const column of this.columns) {
          group[column] = item[column]
        }
      } else {
        const row = {}
        for (const column of this.columns) {
          row[column] = item[column]
        }
        rows.push(row)
      }
    }
    if (group) {
      rows.push(group)
    }
    return rows
  }
}

In this computed attribute, the columns array is used to define the column names of the table, and the rows array is used to define the row content of the table . rows During the initialization process of the array, we traverse the input data array and convert it into row objects according to the type. If the type of the current row is group, it means that this is a summary row, and we need to create a new summary row object; if the type is item, it means that this is an ordinary row, and we A new normal row object needs to be created. When creating a row object, we use the column names defined by the columns array to assign the attribute value of each element to the corresponding column of the row object. Finally, we put all the row objects into the rows array and return it.

With this table component, we can use Vue to implement the grouping and merging functions of tables. We only need to pass a data object containing student grades to the table component and implement the above functions in the component. When rendering a table, the component automatically merges adjacent ordinary rows into a group and displays summary information below the group.

In short, it is very simple to use Vue to implement the grouping and merging function of tables. You only need to convert the data into a format suitable for the table and implement the corresponding rendering logic in the table component. This feature not only improves the usability and user experience of the table, but also allows users to better understand and analyze the data.

The above is the detailed content of How to group and merge tables in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn