📜  vuetify table 使所有列都可编辑 (1)

📅  最后修改于: 2023-12-03 15:21:05.661000             🧑  作者: Mango

Vuetify Table: Enable Editing for all Columns

  • Vuetify is a popular UI framework for Vue.js that provides a wide range of ready-to-use components.
  • The v-data-table component in Vuetify allows you to display tabular data with various features like sorting, searching, pagination, etc.
  • By default, the v-data-table does not allow editing of individual cells. However, with some customizations, you can enable editing for all columns.
Steps to Enable Editing for all Columns
  1. Import the necessary components and styles from Vuetify:
<template>
  <v-data-table
    :headers="headers"
    :items="items"
    @item.edited="saveChanges"
  ></v-data-table>
</template>

<script>
import { VDataTable, VTextField } from 'vuetify/lib' 

export default {
  components: { VDataTable, VTextField },
  //...
}
</script>

<style>
@import '~vuetify/dist/vuetify.min.css';
@import '~vuetify/lib/services/colors';

.v-data-table tbody tr:hover td {
  background-color: $pink lighten-4 !important;
}
</style>
  1. Define your table data in the script section:
export default {
  //...
  data() {
    return {
      headers: [
        { text: 'Name', value: 'name' },
        { text: 'Email', value: 'email' },
        { text: 'Phone', value: 'phone' }
      ],
      items: [
        { name: 'John Doe', email: 'john@example.com', phone: '(123) 456-7890' },
        { name: 'Jane Smith', email: 'jane@example.com', phone: '(987) 654-3210' }
      ]
    }
  },
  //...
}
  1. Create a custom slot for each column where you want to enable editing:
<template>
  <v-data-table
    :headers="headers"
    :items="items"
    @item.edited="saveChanges"
  >
    <template v-slot:item.name="{ item, edit }">
      <v-text-field v-model="item.name" @keyup.enter="edit(false)" dense hide-details></v-text-field>
    </template>
    <!-- Repeat this for other columns -->
  </v-data-table>
</template>
  1. Add a method to handle saving the changes made to the table:
export default {
  //...
  methods: {
    saveChanges(item) {
      // Implement your logic to save changes made to the table
      console.log(item);
    }
  },
  //...
}

This will enable editing for all columns in the Vuetify table. When a user edits a cell and presses Enter, the @item.edited event will be triggered along with the updated item data. You can then handle this event in the saveChanges method to perform any necessary actions, such as updating the backend or storing the changes locally.

Make sure to adjust the code according to your exact requirements and the structure of your data.

Please note that this answer assumes you are using the latest version of Vuetify (v2.x). If you are using an older version, some syntax or component names may be different.