Asked By: Anonymous
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?
Solution
Answered By: Anonymous
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', {_x000D_
template: '#child-tpl',_x000D_
props: ['child', 'index']_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
children: ['a', 'b', 'c', 'd']_x000D_
},_x000D_
methods: {_x000D_
reverse: function () {_x000D_
this.children.reverse();_x000D_
}_x000D_
}_x000D_
});
_x000D_
<a href="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js">//cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js</a>_x000D_
<template id="child-tpl">_x000D_
<div>I'm {{child}}, {{index}}</div>_x000D_
</template>_x000D_
_x000D_
<div id="app">_x000D_
<child v-for="(child, index) in children" :child="child" :index="index"></child>_x000D_
<button @click="reverse">Reverse</button>_x000D_
</div>
_x000D_
_x000D_
x000D