Vue custom events in loop

Viewed 414

When displaying components using v-for, the events emitted by the child component are not triggered (custom event update). The standaline component works as it should.

I don't understand how to deal with the problem.

main.js

import Vue from "vue";
import App from "./App.vue";

new Vue({
  render: (h) => h(App)
}).$mount("#app");

App.vue

<template>
  <div id="app">
    <h1>It work</h1>
    <Inner v-on:update="this.do" />
    <h1>It NOT work</h1>
    <Inner v-for="n in [1, 2, 3]" :key="n" v-on:update="this.do" />
  </div>
</template>

<script>
import Inner from "./Inner";

export default {
  name: "App",
  components: { Inner },
  methods: {
    do() { alert(1); },
  },
};
</script>

Inner.vue

<template>
  <button v-on:click="this.do">CLICK ME</button>
</template>

<script>
export default {
  name: "Inner",
  methods: {
    do() { this.$emit("update"); },
  },
};
</script>
1 Answers

do is a keyword in JavaScript, try naming the methods another name without using this in order to use the component. Here is a demo:

const Inner = Vue.component('Inner', {
  template: '#Inner',
  methods: {
    clicked() { this.$emit("update"); },
  },
});

new Vue({
  el:"#app",
  components: { Inner },
  methods: {
    clicked() { alert(1); },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template id="Inner">
  <button v-on:click="clicked">CLICK ME</button>
</template>

<div id="app">
  <h1>It NOT work</h1>
  <Inner v-for="n in [1, 2, 3]" :key="n" v-on:update="clicked" />
</div>

Related