Skip to content

Instantly share code, notes, and snippets.

@jarektkaczyk
Last active March 18, 2016 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarektkaczyk/d0f89852205ec1ab69cb to your computer and use it in GitHub Desktop.
Save jarektkaczyk/d0f89852205ec1ab69cb to your computer and use it in GitHub Desktop.
how to remove given child component from parent's array (including dynamically added elements) ?
<div id="some-id">
<category v-for="category in categories"
:id="category.id"
:name.sync="category.name"
</category>
// we add items to the categories array dynamically
<button @click="categories.push({})">Add categories</button>
</div>
Vue.component('category', {
props : ['id', 'name'],
// how to remove given element here?
template : `<div>{{ name }} <button @click="remove">X</button></div>`
}
new Vue({
el : '#some-id',
data : {
categories : [{ id : 1, name : 'cat name' }, ... ]
}
})
@LinusBorg
Copy link

the clean way would be to dispatch an event to the parent component with the category to remove (to prevent tight coupling of the components. you could access the categories in the parent component from the child through this.$parent.categories, but that's discouraged for the aforementioned reason)

<div id="some-id">
  <category v-for="category in categories"
          :category="category"
  </category>

  // we add items to the categories array dynamically
  <button @click="categories.push({})">Add categories</button>

</div>

Vue.component('category', {
  props : ['category'],
  methods: {
    remove: function(category) { this.$dispatch('removeEvent', category) }
  }
  template : `<div>{{ category.name }} <button @click="remove(category)">X</button></div>`
}

new Vue({
  el : '#some-id',
  data : {
      categories : [{ id : 1, name : 'cat name' }, ... ]
  },
  events: {
    removeEvent: function(category) { this.categories.$remove(category) }
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment