【问题标题】:vuejs how to get index of child from child methodvuejs如何从子方法获取子索引
【发布时间】:2017-03-10 16:13:00
【问题描述】:

我有组件:

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

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

【问题讨论】:

  • 你能在使用 child 的地方添加代码吗?

标签: vue.js vuejs2 vue-component


【解决方案1】:

将索引作为道具传入。索引来自孩子之外的某个地方,因此孩子应该将其作为道具接收。孩子中不应该有任何方法可以向父母查询信息。孩子需要从外部获得的一切都应该作为道具传递给它。

在下面的sn-p中,索引由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>

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2020-06-04
    • 1970-01-01
    • 2021-04-25
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多