Search code examples
vue.jsvuejs3vue-componentvuetify.jsvuetifyjs3

How to prevent the selected state from being released when an already selected element in v-list of vuetify3


How to prevent the selected state from being released when an already selected element is reselected.

using vue3, vuetify3 v-list consists of v-list-item, v-list-group and children of v-list-group.

I am developing something similar to the one in that link. When you click Users > Actions > Create for the first time, it is grayed out, but when you click again, it is deselected. What should I do to prevent my selection from being cancelled?

vuetify playground demonstrating the behavior.

We developed it so that which item was selected can be stored as selectedItem. However, it didn't solve the UI-wise deselection.

The value is stored in selectedItem.

Is there a way to add or delete .v-list-item--active by comparing it to what is stored in selectedItem for every element?
Can't we control the content with v-model:selected="selectedItem"?


Solution

  • You need two parts:

    1. A variable controlling the selected model (bound to the list's v-model:selected). According to docs: "An array containing the values of currently selected items.". In reality, it's an array of their ids, not their values.
    2. A method bound on the list's @click:select (documented here). On deselect (if !value), reselect (this.selected.push(id)).
      Note it only works if wrapped in this.$nextTick() as the model update triggered by the click happens after the callback bound on @click:select is called.

    See it working.


    <script>:

    //...
      data: () => ({
        selected: []
      }),
      methods: {
        reselect({ value, id }) {
          if (!value) {
            this.$nextTick(() => {
              this.selected.push(id)
            })
          }
        }
      }
    //...
    

    <template>:

    <v-list
      @click:select="reselect"
      v-model:selected="selected"
    >
      <!-- ... -->
    </v-list>