Reputation: 2512
I have component:
Vue.component('child', {
template : '#child-tpl',
props : {
child : Object
}
},
methods : {
index : function () {
return ???; // current index
}
}
});
This children can be reorder/remove/add dinamically. Need store actual current index of this children. How to get current index for target child of parent children array?
Upvotes: 1
Views: 4295
Reputation: 43881
Pass index in as a prop. The index is coming from somewhere outside the child, so the child should receive it as a prop. There should not be any methods in a child that query parents for information. Everything a child needs from outside itself should be passed to it as props.
In the snippet below, the index is conveniently provided by the v-for
.
Vue.component('child', {
template: '#child-tpl',
props: ['child', 'index']
});
new Vue({
el: '#app',
data: {
children: ['a', 'b', 'c', 'd']
},
methods: {
reverse: function () {
this.children.reverse();
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js"></script>
<template id="child-tpl">
<div>I'm {{child}}, {{index}}</div>
</template>
<div id="app">
<child v-for="(child, index) in children" :child="child" :index="index"></child>
<button @click="reverse">Reverse</button>
</div>
Upvotes: 7