$emit 从子项到 VueJS 中 v-for 内的父项的事件

$emit event from children to parent item that is inside a v-for in VueJS

假设我有以下结构:

// parent template
<div v-for="item in items">
   <span>Parent</span>
   <children1>
      // inside children1, i got another children
      <children2 @on:finished="onFinished"></children2>
      <button>Click me</button>
   </children1>
</div>

然后在 children1 methods 我会有这样的东西来听 children2:

methods: {
    onFinished: function () {
       // Here i would like to disable `click me` button and change its text for this particular item inside the iteration
    }
}

来自 children2 我只是在其中完成某些操作后才执行此操作。

this.$emit('on:finished', true)

正如我在方法内部所写的那样,我希望能够使用 VueJS 仅通过其子项的 $emit 更改其中一项。但是我在考虑使用数据属性,但这会影响整个模板,使用计算的怎么样?那行得通吗?但是如何呢?

有什么建议吗?

您似乎缺少数据属性来跟踪每个 child 组件的禁用状态。查看此示例是否是您要查找的内容,单击每个 child 的完成按钮将禁用另一个按钮:

Vue.component('child-component', {
  props: ['disabled', 'text'],
  template: `<div><button :disabled="disabled">{{ text }}</button><button @click="$emit('finished')">Finish</button></div>`
})

new Vue({
  el: '#app',
  data () {
    return {
      children: []
    }
  },
  mounted () {
    this.children = Array.from(Array(10), (x,i) => {
      return {
        id: i,
        disabled: false,
        text: 'Click Me'
      }
    })
  },
  methods: {
    onFinished (e, i) {
      this.children[i].disabled = !this.children[i].disabled
      this.children[i].text = this.children[i].disabled ? 'Disabled' : 'Click Me'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <span>Parent</span>
  <child-component :disabled="child.disabled" :text="child.text" v-for="(child, i) in children" @finished="onFinished($event, i)" :key="child.id"></child-component>
</div>

首先,您需要正确收听

发出的 child
  <div v-for="(item,index) in items">
   <span>Parent</span>
   <children :myIndex='index' @finished="onFinished"></children>
   <button>Click me</button>
  </div>

请注意,我还向您的 child 添加了一个索引,必须在您的 child 组件

中将其作为 prop 接受
props:[myIndex]

其中 onFinished() 是 parent 组件中的一个方法。

在你的 child 组件中,像这样发出

this.$emit('finished', {state: true, index: myIndex})

现在,您可以在您的方法中使用这个索引-

onFinished(itemState){
this.items[itemState.index].state = itemState.state
}

您可以使用项目的索引来改变他的状态。

    data: function () {
     items: [
       {
          enabled: true  
       },
       {
          enabled: true
        }
    ]

禁用功能:

disableItem (index) {
  this.items[index].enabled = false
}

在模板中:

<div v-for="(item, index) in items">
<span>Parent</span>
<children @on:finished="disable(index)"></children>
<button>Click me</button>
</div>