2017-03-10 186 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