Just starting out with VueJS and working on my first project. I have a list of products that I want to sort by price. I created two components - a parent and a child component for the dropdown button. I've been trying to pass a sort method from the child component to the parent by emitting an event, but no matter how many times I try, I can't seem to figure out what's wrong in my code. Any assistance would be greatly appreciated!
Child Component Code:
<template>
<div class="dropdown">
<button
@click="toggleShow(); $emit('sortPrice')"
class="dropbtn"
>
{{ title }}
<span class="material-icons-outlined"> {{ icon }} </span>
</button>
<div v-if="showMenu" class="menu">
<div class="menu-item" v-for="(item, index) in this.items" :key="index">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
name: "Dropdown-menu",
props: {
title: String,
icon: String,
items: {
type: Object,
required: true,
},
},
data() {
return {
showMenu: false
};
},
methods: {
toggleShow: function () {
this.showMenu = !this.showMenu;
},
sortPrice: function () {
this.$emit("sort", this.sortPrice);
},
},
};
</script>
Parent Component Code:
<template>
<dropdown
:title="sortedBy"
:items="arrangements"
:icon="material_icons"
@sort="sortByPrice"
></dropdown>
</template>
<script>
import Dropdown from "@/components/Dropdown.vue";
export default {
components: {
Dropdown,
},
data() {
return {
sortedBy: "Featured",
arrangements: ["Featured", "Lowest", "Highest"],
material_icons: "expand_more",
productData: require("@/data/store-data.json"),
};
},
methods: {
sortByPrice: function () {
let realProducts = this.productData.products;
let sortedProducts = realProducts.sort((a, b) => {
if (this.sortedBy === "Highest") {
return b.price - a.price;
} else if (this.sortedBy === "Lowest") {
return a.price - b.price;
}
});
return sortedProducts;
},
},
};
</script>