2017-03-10 187 views
0

得到孩子的指数我有分量:vuejs如何从孩子的方法

Vue.component('child', { 
    template : '#child-tpl', 
    props : { 
     child : Object 
     } 
    }, 
    methods : { 
     index : function() { 
      return ???; // current index 
     } 
    } 
}); 

这孩子可以重新排序/删除/添加dinamically。需要存储这个孩子的实际当前指标。 如何获得父母孩子数组的目标孩子的当前索引?

+0

你可以添加在正在使用孩子的代码? – Saurabh

回答

1

传递索引作为道具。该指数来自孩子以外的某个地方,所以孩子应该将其作为道具接受。在查询父母信息的小孩中不应该有任何方法。儿童从外面需要的一切都应该作为道具传递给它。

在下面的代码片段中,索引由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>

+0

谢谢!!!!!!!!!!! – Deep