Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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>

I think I am missing something really important here but I believe using track-by="uuid" will allow me to grab the index of that respective object so I can do an array operation on that object. My example does not return the index of the object.

1) what does track by id really do in Vue.js ?

2) How to I get a return for my objects index? track-by="$index" does not work for objects array but only a simple array. I need a solution that gives me the index from track-by="uuid"

share|improve this question

'track-by' is only used to hint Vue so that it can track each node’s identity, and thus reuse and reorder existing elements.

It's not something you can access in a method, it's used by Vue internals only.

Therefore, you have to refer to each object's uuid on the click events, like so:

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

However, I think what you are looking for is the following:

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

v-for also supports an optional second argument for the index of the current item. That's the 'Vue way' to pass an item's index in a v-for loop.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.