Discover the steps to retrieve a list of products within a specific category using Vue.js

Hey there! I'm a newbie to vue and I've got myself a bunch of json data that includes products categorized by category. Can someone guide me on how to display each product under its respective category?

{
    "_id": "62566ec30e42d6c5ab370e7c",
    "products": [],
    "type": "mobile phone",
    "__v": 0
}

Here's a peek at my product array:

{
    "_id": "625671db370e769a8a93a510",
    "reviews": [],
    "owner": {
        "_id": "6220db7ee861f3dbbaf21e3d",
        "name": "mr jacob",
        "about": "hello",
        "__v": 0
    },
    "category": {
        "_id": "62566ec30e42d6c5ab370e7c",
        "products": [],
        "type": "mobile phone",
        "__v": 0
    },
    "title": "galaxy s21",
    "description": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus ullam iusto culpa assumenda enim ea, asperiores omnis, facere quos animi doloremque, architecto facilis aut? Nobis ab sit iusto praesentium quia.",
    "photo": "https://ajibade.s3.amazonaws.com/1649832365317",
    "price": 500,
    "stockQuantity": 1,
    "__v": 0,
    "id": "625671db370e769a8a93a510"
}

Now let's check out my html template responsible for listing categories from the database:

<div class="container" v-for="category in categories" :value="category._id" :key="category._id">
      <span>{{category.type}}</span>
    </div>

Check out my script tag too:

<script>
export default {
  name: "Products",
  name: "categories",
  data() {
    return {
      categoryID: null,
      categories: [],
      products: [],
     
    };
  },

 
  mounted() {
    axios.get("http://localhost:5000/api/products").then(res => {
      console.log(res);

      this.products = res.data.products;
    });
    axios.get("http://localhost:5000/api/categories").then(res => {
      console.log(res);

      this.categories = res.data.categories;
    });
  }
};
</script>

I'd really appreciate some pointers on filtering these products by category. Feeling a bit lost here!

Answer №1

You have the option to create an inner loop for products within a specific category by passing category._id to a method:

new Vue({
  el: "#demo",
  data() {
    return {
      categoryID: null,
      categories: [],
      products: [],
      show: null
    };
  },
  methods: {
    productsForCat(cat) {
      return this.products.filter(p => p.category._id === cat)
    },
    displayProd(id) {
      this.show === id ? this.show = null : this.show = id
    }
  },
  mounted() {
    /*axios.get("http://localhost:5000/api/products").then(res => {
      console.log(res);
      this.products = res.data.products;*/
    //});
    this.products = [
          {"_id": "625671db370e769a8a93a510", "reviews": [], "owner": {"_id": "6220db7ee861f3dbbaf21e3d", "name": "mr jacob", "about": "hello", "__v": 0}, "category": {"_id": "62566ec30e42d6c5ab370e7c", "products": [], "type": "mobile phone", "__v": 0}, "title": "galaxy s21", "description": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus ullam iusto culpa assumenda enim ea, asperiores omnis, facere quos animi doloremque, architecto facilis aut? Nobis ab sit iusto praesentium quia.", "photo": "https://ajibade.s3.amazonaws.com/1649832365317", "price": 500, "stockQuantity": 1, "__v": 0, "id": "625671db370e769a8a93a510"},
          {"_id": "625671db370e769a8a93a511", "reviews": [], "owner": {"_id": "6220db7ee861f3dbbaf21e3d", "name": "mr jacob", "about": "hello", "__v": 0}, "category": {"_id": "62566ec30e42d6c5ab370e7d", "products": [], "type": "mobile phone", "__v": 0}, "title": "galaxy", "description": "Lorem ipsum dolor sit amet consectetur ...
        ]
    /*axios.get("http://localhost:5000/api/categories").then(res => {
      console.log(res);
      this.categories = res.data.categories;*/
    //});
    this.categories = [
        {"_id": "62566ec30e42d6c5ab370e7c", "products": [], "type": "mobile phone", "__v": 0}, {"_id": "62566ec30e42d6c5ab370e7d", "products": [], "type": "phone", "__v": 0}
      ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div class="container" v-for="category in categories" :key="category._id">
    <span @click="displayProd(category._id)">{{category.type}}</span>
    <div v-if="category._id === show">
      <li v-for="product in productsForCat(category._id)" :key="product._id">
        {{ product.title }}
      </li>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript - changing object into a string (not functioning properly)

Looking to convert a JavaScript object into a string? Here's an example: var obj = {"name": "XXX", "age": "27"}; After doing some research, I found out about JSON.stringify(obj); JSON.stringify(obj); works perfectly when the IE8 modes are set as fo ...

Executing server-side method with jQuery in .Net 1.1

Currently, I am utilizing .net1.1 and attempting to invoke a server-side method using jQuery upon clicking the browser's Close button. However, my code does not seem to be functioning correctly. I have provided my code below for reference. Can anyone ...

Display the div based on the choices made in both select elements

Image of code is currently not accessible on this device Apologies for the lack of visual aid, I have coded on a different device. I am looking for a way to make the div appear based on certain options selected from both dropdown menus. Any assistance wit ...

Unusual CSS rendering hiccup

Using jQuery, I am manipulating the display of an <a> element. Depending on certain keypress events, it adds or removes a class from an <input> element (which controls the display) that is related as a sibling to the mentioned <a>. The i ...

"Utilize an AJAX call to dynamically retrieve and add results for every PHP loop

I currently have a functional AJAX request that calls a PHP file with some looping actions. Depending on certain parameters, the request can take several minutes to complete, which is not ideal for user experience. How can I modify my code so that results ...

Creating unique identifiers and names for dynamically generated editable HTML table cells using JavaScript

Clicking the button will trigger the GenerateTable() function to dynamically create a table based on selected options from the drop-down menu as column headings. Below is the JavaScript code, along with instructions on how to assign IDs and names to each t ...

CKEditor - extracting modified content with its associated HTML markup

I am currently developing my own custom Drupal plugin and I recently reviewed the code provided in the API for change events: editor.on('change', function (evt) { console.log(this.getData()); }); Using this code snippet, I am able to vi ...

Adjust the CSS property of a div to have a fixed position when scrolling

I attempted to implement a fixed div on scroll in Vue.js using the following code: ... async created() { window.addEventListener('scroll', this.calendarScroll); } methods: { calendarScroll() { console.log('Scroll'); cons ...

Adding a dynamic form to each row in a table: A step-by-step guide

https://i.sstatic.net/HctnU.jpg Hey there! I'm facing a challenge with dynamically generated rows in a form. I want to send only the inputs from the selected row when a checkbox is clicked. Can you help me figure this out? I tried using let rowForm ...

What is the best way to conceal an HTML element on a particular page that is already styled as (visibility: visible), but only if its child has a specific class assigned to it?

I have a grid of content and posts displayed on multiple webpages. Users can select specific items from the grid to navigate to more detailed information on another page. Each webpage has its own grid which I want to filter based on a specific class. The ...

Organize Development and Production files in npm or webpack for improved efficiency

In React Native projects, we typically use index.android.js and index.ios.js to differentiate between the same file for Android and iOS platforms. But I wonder if it's possible to separate files based on the development and production environments as ...

Error encountered while attempting to send a post request via Axios due to network

I am currently working on implementing a post request in my application using Axios. Unfortunately, I have run into some errors while trying to make the post request. Here is the code snippet for making the post request: onPostJson = () => { axios.po ...

Stylish CSS Card with set height and adaptive image

Looking for a way to set a fixed height for a file input with preview? Check out this Codepen example: Codepen In the HTML (vue component), there is a card element with an image that maintains its aspect ratio. However, you may want to fix the height of ...

Harnessing the power of Promise to verify the completion of a filestream

After initializing the variables below, I update them while parsing through a large CSV file, which can be time-consuming. var yearTotal2008 = 0; var year2008TallyByPatient = {}; To process the CSV file, I use the following function: const produceChart ...

Is it feasible to include a variable interpolation in the package.json file for a Node Package?

I have a static website where I compile Sass using the node-sass library. Currently, I am using Grunt to watch the files, but I feel like it's unnecessary because I could just use their built-in command line interface (CLI). So, I decided to add thi ...

Deconstructing JSON arrays in Flutter

I'm having difficulties parsing a JSON file that contains an array. The structure of the JSON file looks like this: { "status": "200", "addresses": [ { "address": "Address 1" }, { "address": "A ...

What is causing the javascript in my svg files not to function when embedded in an html document?

I have the following code for an SVG: <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="470px" height="260px" version="1.1" onload="addEvent ...

Guide on sending JSON data in an HTTP request for Windows Phone

Does anyone know the best way to send or post a JSON HTTP request in Windows Phone 7? I have been using XML HTTP requests successfully for sending and posting with parameters. However, when I attempt to use JSON, I encounter errors. Can someone advise me ...

Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this: history: { Movies: Array<Media>, Images: Array<Media>, Music: Array<Medi ...

Cannot convert a JSONObject to a JSONArray data type

After returning a string from another activity and attempting to convert it into a JSONArray, I encountered the following error: 08-22 14:51:35.313: E/YourCartActivity(1134): Error parsing data org.json.JSONException: Value {"yourCart_totalPrice":"5500.0 ...