vue3中查找字典列表中某个元素的值对应的列表索引值

vue3中查找字典列表中某个元素的值对应的列表索引值

目录

思路方法

要获取字典列表中某个元素的值对应的列表索引值,可以使用数组的 findIndex 方法。这个方法返回数组中满足提供的测试函数的第一个元素的索引。如果没有找到,则返回 -1。

代码实现示例

html 复制代码
<template>
  <div>
    <p>查找的结果: {{ foundObject }}</p>
    <p>索引值: {{ index }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'jack' },
        { id: 2, name: 'jason' },
        { id: 3, name: 'tom' }
      ],
      searchId: 2, // 我们想查找的对象的 id
      foundObject: null, // 存储查找到的对象
      index: -1 // 存储查找到的对象的索引值
    };
  },
  mounted() {
    this.findObjectAndIndexById();
  },
  methods: {
    findObjectAndIndexById() {
      // 首先使用 findIndex 方法查找索引值
      this.index = this.items.findIndex(item => item.id === this.searchId);
      
      // 如果找到了索引值,则使用索引值从数组中获取对象
      if (this.index !== -1) {
        this.foundObject = this.items[this.index];
      } else {
        // 如果没有找到,则重置 foundObject
        this.foundObject = null;
      }
    }
  }
};
</script>

解释说明

  • index 变量用于存储查找到的对象的索引值。
  • findObjectAndIndexById 方法首先使用 findIndex 方法查找 items 数组中满足 id 等于 searchId 的对象的索引值,并将其存储在 index 中。
  • 如果 index 不等于 -1(表示找到了对象),则使用 index 从 items 数组中获取对应的对象,并将其存储在 foundObject 中。
  • 如果 index 等于 -1(表示没有找到对象),则将 foundObject 重置为 null。
相关推荐
2013编程爱好者15 分钟前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
是小胡嘛1 小时前
C++之Any类的模拟实现
linux·开发语言·c++
小满zs1 小时前
Next.js第十一章(渲染基础概念)
前端
csbysj20202 小时前
Vue.js 混入:深入理解与最佳实践
开发语言
不羁的fang少年2 小时前
前端常见问题(vue,css,html,js等)
前端·javascript·css
change_fate2 小时前
el-menu折叠后文字下移
前端·javascript·vue.js
yivifu2 小时前
CSS Grid 布局详解(2025最新标准)
前端·css
Gerardisite3 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5953 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan4 小时前
【C++】多态
开发语言·c++