You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Vuetify列表的选中项或索引?v-model绑定失效问题

Vuetify列表选中项获取与图片预览实现方案

首先明确:Vuetify的<v-list>组件本身不支持v-model绑定选中值,你看到的灰色背景是组件默认的激活状态(focus/hover后的视觉反馈),不会自动同步到你的selection变量。

你的核心需求思路完全可行——通过响应式状态imgpath绑定<v-img>的src,列表选中后更新该状态来切换图片,这个方案是合理的。

以下是修正后的实现代码:

<template>
  <v-app>
    <v-main>
      <v-card>
        <v-list>
          <!-- 遍历生成列表项,绑定点击事件和选中状态 -->
          <v-list-item
            v-for="(item, index) in items"
            :key="index"
            :title="item.title"
            :value="item.value"
            @click="handleSelect(item)"
            <!-- 通过active-class标记当前选中项 -->
            :class="{ 'v-list-item--active': selection === item.value }"
          >
          </v-list-item>
        </v-list>
      </v-card>

      <v-card class="mt-5">
        <p>当前选中值:{{ selection }}</p>
        <!-- 预览选中的图片 -->
        <v-img 
          :src="imgpath" 
          class="mt-2"
          height="200"
          contain
        ></v-img>
      </v-card>
    </v-main>
  </v-app>
</template>

<script>
export default {
  data: () => ({
    selection: 1,
    imgpath: '',
    items: [
      { title: '图片1', value: 0, imgUrl: '/path/to/image1.jpg' },
      { title: '图片2', value: 1, imgUrl: '/path/to/image2.jpg' },
      { title: '图片3', value: 2, imgUrl: '/path/to/image3.jpg' },
    ],
  }),
  methods: {
    handleSelect(item) {
      // 更新选中值
      this.selection = item.value;
      // 更新图片路径
      this.imgpath = item.imgUrl;
    },
  },
  // 初始化时设置默认图片
  mounted() {
    const defaultItem = this.items.find(item => item.value === this.selection);
    if (defaultItem) this.imgpath = defaultItem.imgUrl;
  },
};
</script>

关键改动说明:

  • 移除<v-list>上无效的v-model,改为遍历生成<v-list-item>并绑定点击事件
  • 通过handleSelect方法同步更新selection和imgpath两个响应式状态
  • 用:class绑定选中样式,确保视觉上的选中状态与数据一致
  • 在items数组中新增图片路径字段,方便点击时直接获取

内容的提问来源于stack exchange,提问作者LemonGraZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:16