3

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"

1 Answer 1

1

'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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.