vue.jsselectdatatablevuetify.js

Vuetify data table in single-select mode, selecting one row selects all others


I am trying to select one row in the table and emit the selected item.

Selecting one selects all but only the first encountered object is saved to the model (as selected variable).

Do you have any ideas, what i'm doing wrong?

enter image description here

<template>
  <v-data-table
    :headers="headers"
    :items="items"
    :search="search"
    :loading="loading"
    v-model="selected"
    single-select
    show-select
    :options="{itemsPerPage:5}"
    @item-selected="itemSelected"
  >
    <template v-slot:top>
      <v-toolbar flat>
        <v-text-field
          v-model="search"
          append-icon="mdi-magnify"
          label="Search"
          single-line
          hide-details
        ></v-text-field>
      </v-toolbar>
    </template>

    <template v-slot:item.name="{ item }">{{ item.name }}</template>
  </v-data-table>
</template>

<script>
export default {
  name: "variable-selector",
  props: ["variables", "map", "index"],
  data() {
    return {
      search: "",
      selected: {},
      loading: false,
      items: [],
      headers: [{ text: "Variable name", value: "name", sortable: true }]
    };
  },
  methods: {
    itemSelected(selection) {
      if (selection.value) {
        this.$emit("selected", selection.item); // it always emits var_2 object
      } else {
        this.$emit("selected", null);
      }
    },

    updateItemsList(variables) {
      this.items = Array.from(variables);
    }
  },

  mounted() {
    this.updateItemsList(this.variables);
  },

  watch: {
    variables(newValue) {
      this.loading = true;
      this.updateItemsList(newValue);
      this.loading = false;
    }
  }
};
</script>

Solution

  • Each object should be unique key value if u face error , you want manually tell each object is unique

    just add

    item-key="table_header_index"//or name 
    

    eg:

    <v-data-table
        :headers="headers"
        :items="items"
        show-select
        item-key="table_header_index"  <-------------------add this line
    >
    
    </v-data-table>