VSelect - selection not working with custom "item" slot in Vuetify 3
Asked Answered
G

1

6

I am using VSelect from Vuetify 3 in my Vue 3 app and I am trying to use item slot. But my VSelect options become unpickable

I have this VSelect element:

 <v-select
    v-model="tag"
    :items="tags"
    variant="solo"
    label="Tags" >
    <template #item="{ item }" >
      <v-list >
        <v-list-item :title="item.title" />
      </v-list>
    </template>
  </v-select>

tag and tags in data:

  tag: null,
  tags: [
    { title: 'example1', value: 0 },
    { title: 'example2', value: 1 },
  ],

in the output I have this select with options, but options are not pickable:

output

So how can I set a slot "item" to VSelect component in Vuetify 3 with pickable options?

Greenfinch answered 15/3, 2023 at 7:33 Comment(0)
D
6

The props object handed to the slot contains an onClick callback, and you need to bind it in order for selection to work:

<template #item="{ item, props: { onClick } }" >
  <v-list-item :title="item.title" @click="onClick"/>
</template>

The documentation is a bit sparse at the moment and gives the type as Record<string, unknown>. In Vuetify 3.4, the other values are key, title, value and ref, a template ref from the underlying VVritualScroll used to update height of the scroller.

When using a component with a title prop (like VListItem), you can just bind the whole props object:

<template #item="{ props }" >
  <v-list-item v-bind="props"/>
</template>

(Btw. the #item slot already renders its content into a v-list, there is no need to wrap it again)

Here it is in a snippet:

const { createApp, ref } = Vue;
const { createVuetify } = Vuetify
const vuetify = createVuetify()
createApp({
  setup(){
    
    return {
       tag: ref(null),
        tags: [
          { title: 'example1', value: 0 },
          { title: 'example2', value: 1 },
        ],
    }
  }
}).use(vuetify).mount('#app')
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<div id="app" class="d-flex justify-center">
  <v-app>
    <div>
    <v-select
      style="width: 300px;"
      v-model="tag"
      :items="tags"
      variant="solo"
      label="Tags"
    >
      <template #item="{ item, props: {onClick, title, value} }" >
        <v-list-item :title="item.title"  @click="onClick"/>
      </template>
    </v-select>
      
      Selected: {{tag}}
    </div>
  </v-app>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
Duet answered 15/3, 2023 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.