[Vuejs]-Is this TypeError linked to a wrong this.$emit?

2👍

There’s two problems:

  1. You _.filter returns an arry, so you don’t emit the user, but an array containing the user. That filter is also completely unnecessary, because palready is the user object that you intend to filter for. But that code is not the cause of the error.
  2. v-on:delete-id="who" ere you pass an object (who) to the event listener, but it expects a function. That’s what’s raising the error.

A working version of your code would look like this:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      this.$emit('delete-id', p)
    }
  }
})

var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  },
  methods: {
    handleDelete(person) {
      const index = this.who.indexOf(person)
      this.who.splice(index, 1)
    }
  }
})
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="handleDelete"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template>

0👍

Following up on Linus’ excellent answer, for the record below is my corrected code which emits and Array as when a user is deleted.

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
                var user = _.filter(this.who, function (w) {
                return w.id != p.id
            })
      this.$emit('delete-id', user)
    }
  }
})

var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  },
  methods: {
    handleDelete(users) {
      this.who = users
    }
  }
})
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="handleDelete"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template>
👤WoJ

Leave a comment