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:
<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>
This Parent Component:
<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>