javascript - Vue.js 使用对象数组中的唯一 id 来获取对象的索引?

标签 javascript vue-component vue.js

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) track by 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 方式”。

关于javascript - Vue.js 使用对象数组中的唯一 id 来获取对象的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569893/

相关文章:

javascript - window.opener 没有改变

javascript - 如何取消加载图像

javascript - iPad 书签不弹出

javascript - 链接上的 jQuery Datatable javascript 不适用于多个页面

vue.js - 如何在html参数中添加槽?

javascript - 如何在模板的原始 HTML/x 引用 ID 元素中引用 VueJS 组件的名称?

javascript - 如何使用 Vue JS 在 HTML 的同一标记中使用 "v-if"和 "v-else"?

events - Vue 事件修饰符防止与停止

javascript - 如何在 Linnworks 嵌入式应用程序中获取刷新的 token ?

vue.js - 以样式传递Vuejs数据(SFA)