How do I get the selected item / index of from a vuetify list?
Applying v-model
to the <v-list>
tag does not work somehow and I can not find any working example.
I'd like to have a list of images / file names and then display the selected image. My idea was to have an <v-img :src="imgpath">
and then imgpath
beeing a reactive state that is changed via the list. Or is my idea completely wrong?
Minimum example of my try:
<template>
<v-app>
<v-main>
<v-card>
<v-list v-model='selection' :items='items'></v-list>
</v-card>
<v-card class='mt-5'>
{{ selection }}
</v-card>
</v-main>
</v-app>
</template>
<script>
export default {
data: () => ({
selection: 1,
items: [
{ title: 'Item 0', value: 0 },
{ title: 'Item 1', value: 1 },
{ title: 'Item 2', value: 2 },
],
}),
}
</script>
Expected behaviour:
The selection
state changes according to the selected item in the list.
Observed behaviour:
Visually the selection changes (a different item is marked with a gray background), but the selection
does not change.
It's super un-obvious how to do what you want, and there are no examples in the Vuetify documentation for what you'd think was a pretty common use-case.
The trick is to ignore v-model
and instead use an @click
event and the :active
attribute of v-list-item
.
Template:
<template>
<v-list>
<v-list-item v-for="item in items"
:key="item.id"
:active="item.id === selected"
@click="selected = item.id">
Script:
<script setup lang="ts">
import { ref } from "vue";
const selected = ref("");
You can now do all the obvious stuff with multiple select etc and anything else you might want.