Vue.js在我的对象数组中使用唯一 id 来获取我的对象的索引

Vue.js using unique id in my objects array to grab the index of my object?

本文关键字:对象 我的 id 获取 索引 唯一 js 数组 Vue      更新时间:2023-09-26

Vue.component('post', {
  template: "#my-component",
  props: ['posty'],
  methods: {
  	testFunc: function(index){
  		 this.$parent.parentMethod(index);
  	}
  }
});
var vm = new Vue({
  el: "#app",
  data: {
    posts: [{	uuid: '88f86fe9d',
				title: "hello",
				votes: '15'
			},
			{	
				uuid: '88f8ff69d',
				title: "hello",
				votes: '15'
			},
			{	
				uuid: '88fwf869d',
				title: "hello",
				votes: '10'
			}]
  },
  methods: {
  	parentMethod: function(index){
  		this.posts.splice(index, 1)
  	}
  }
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  
<div id="app">
  <div class="container-fluid">
    <ul class="list-group">
      <post v-for="posty in posts" :posty="posty" track-by="uuid"></post>
    </ul>
  </div>
</div>  
  
<template id="my-component">
	<div v-if="posty.votes === '15'">
	  <button v-on:click="testFunc(uuid)">{{posty.title}}</button>
	</div>
	<div v-else>
	  <button v-on:click="testFunc(uuid)">No</button>
	</div>
</template>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
  
</body>
</html>

我认为我在这里错过了一些非常重要的东西,但我相信使用 track-by="uuid" 将允许我获取相应对象的索引,以便我可以对该对象执行数组操作。我的示例不返回对象的索引。

1( 按 Id 跟踪在 Vue 中到底做了什么.js?

2( 如何获得对象索引的回报? track-by="$index"不适用于对象数组,而仅适用于简单的数组。我需要一个解决方案,为我提供来自track-by="uuid"的索引

'track-by' 仅用于提示 Vue,以便它可以跟踪每个节点的身份,从而重用和重新排序现有元素。

不是你可以在方法中访问的东西,它只被 Vue 内部使用。

因此,您必须在单击事件中引用每个对象的 uuid,如下所示:

 <button v-on:click="testFunc(posty.uuid)">{{posty.title}}</button>

但是,我认为您正在寻找以下内容:

<ul class="list-group">
  <li v-for="(item, index) in items">
    {{ testMethod(index) }}
  </li>
</ul>

v-for还支持当前项索引的可选第二个参数。这就是在 v-for 循环中传递项目索引的"Vue 方式"。