Skip to content
Advertisement

Why the sort method not working in the parent component?

This is the first project for me in VueJS. I have a product list and want to sort it by price. I built two components and tried to pass a sort method to the parent from the child component (dropdown button) by emitting an event. but after a lot of attempts, I can’t find the wrong with my code, any help!

This Child Component:

JavaScript

This Parent Component:

JavaScript

Advertisement

Answer

Suggestions:

  • emit when an individual item is clicked, not when the button is clicked. You want to emit when the user makes a selection
  • So this means calling the sortPrice function from the menu-item div via @click="sortPrice(item)"
  • Then in the sortPrice function, pass in the item paramter, function (item) { and pass it as a second parameter to your emit call: this.$emit("sort", item);. The parent must know what was selected
  • In the parent component, sortByPrice function, accept the item parameter, sortByPrice: function (item) { and use it to set the sortedBy property: this.sortedBy = item;
  • Do the sorting in a computed property that is then displayed, here in my example called sortedProducts.

For example, the parent:

JavaScript

and the child Dropdown.vue component:

JavaScript
Advertisement