【问题标题】:Get index of object in array onClick VUE3获取数组onClick VUE3中对象的索引
【发布时间】:2021-10-22 03:34:34
【问题描述】:

我已经为此苦苦挣扎了好几个小时! 我真的是 vue 新手,vuex...

我想做的很简单:我在一个数组中有多个对象,我想在点击时获取对象的索引,以便稍后获取该对象中的一些信息。

  • 我点击列表中的一个项目
  • 我得到了索引
  • 然后,我得到了一个查找信息的函数(如 myArr[index].values_.geometry.flatCoordiantes)

这是我的清单:

<ul id="features-list">
      <button
        v-for="(feature, index) in filterByTerm"
        :key="index"
        v-on:click="storeCoords($event, index)"
      >
        {{ feature.values_.name }} {{ index }}
      </button>
    </ul>

这是我的计算:

computed: {
    listedFeatures() {
      return this.$store.getters.GET_ALLFEATURES;
    },
    filterByTerm() {
      return this.listedFeatures.filter((feature) => {
        return feature.values_.name
          .toLowerCase()
          .includes(this.searchInput.toLowerCase());
      });
    },
  },

这是我的方法:

 methods: {
    storeCoords(event) {
      // i'd like to access to coordinate of my object to inject it in another variable
      // this.filterByTerm[event.target.index].values_.coordiantes.etc...
      console.log(this.filterByTerm);

    },
  },
};

如您所见,我 console.log filterByTerm,但我不明白我得到如下内容:

(3) [Proxy, Proxy, Proxy]
0: Proxy
[[Handler]]: Object
[[Target]]: Feature

我真的不知道如何在 [[ stuff ]] 中获得一些信息:s 是的,我的 {{index}} 正在显示当前项目的实际索引。 如果有人能帮忙,那就太好了!

提前致谢

【问题讨论】:

    标签: arrays vue.js vuex vuejs3


    【解决方案1】:

    您可以将迭代器对象传递给绑定中的click-handler:

    <button v-on:click="storeCoords(feature, index)">
    

    然后从对象参数中访问坐标:

    export default {
      methods: {
        storeCoords(feature, index) {
          // assuming the coordinates are stored in `coordinates` prop
          console.log(feature.coordinates)
        }
      }
    }
    

    【讨论】:

    • 好的,非常感谢这个明确的答案,在我停止工作后我有一个小想法,如果我可以检索 feature.values_.name 我可能能够得到其他任何东西,但我错过了“功能”,我明天会试试看,非常感谢!
    • 好的,所以我无法获取控制台日志,但我想它可以工作:o
    • “无法获取console.log”是什么意思?
    • 不,没关系,只是我是 vue 的菜鸟!一切都很好:) 谢谢!
    猜你喜欢
    • 2012-02-21
    • 2020-05-04
    • 2017-06-16
    • 2014-05-14
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多