vuejs 如何从 child 方法获取 child 的索引
vuejs how to get index of child from child method
我有组件:
Vue.component('child', {
template : '#child-tpl',
props : {
child : Object
}
},
methods : {
index : function () {
return ???; // current index
}
}
});
这个children可以reorder/remove/add动态。需要存储这个children的实际当前索引。
如何获取 parent children 数组的目标 child 的当前索引?
将索引作为 prop 传入。该索引来自 child 之外的某个地方,因此 child 应该将其作为道具接收。 child 中不应有任何查询 parents 信息的方法。 child 从外部需要的所有东西都应该作为 props 传递给它。
在下面的代码片段中,索引由 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>
我有组件:
Vue.component('child', {
template : '#child-tpl',
props : {
child : Object
}
},
methods : {
index : function () {
return ???; // current index
}
}
});
这个children可以reorder/remove/add动态。需要存储这个children的实际当前索引。 如何获取 parent children 数组的目标 child 的当前索引?
将索引作为 prop 传入。该索引来自 child 之外的某个地方,因此 child 应该将其作为道具接收。 child 中不应有任何查询 parents 信息的方法。 child 从外部需要的所有东西都应该作为 props 传递给它。
在下面的代码片段中,索引由 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>