Issue with data not being transferred to Vue component

I am currently working on a Vue component that receives an array of 'items' from its parent.

These items are then categorized with two items in each category:

computed: {
        // sort items into categories
        glass: function() {
            return this.items.filter(i => i.category === "glass").slice(0, 2);
        },
        ceramics:
        // etc...

To pass these categorized items as props to another component, I need to place both items in categories.items:

data() {
    return {
        categories: [
            { name: "Glass", sort: "glass", items: {} },
            { name: "Ceramics", sort: "ceramics", items: {} },
            { name: "Brass", sort: "brass", items: {} },
            { name: "Books/Comics", sort: "books", items: {} },
            { name: "Collectibles", sort: "collectibles", items: {} },
            { name: "Pictures", sort: "pictures", items: {} },
            { name: "Other", sort: "other", items: {} }
        ]
    };
},

However, I'm facing issues when passing the data through various lifecycle hooks. The 'items' are fetched using an Axios GET request from the parent component:

methods: {
    fetchItems() {
        let uri = "http://localhost:8000/api/items";
        this.axios.get(uri).then(response => {
            // randomize response
            for (let i = response.data.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [response.data[i], response.data[j]] = [
                    response.data[j],
                    response.data[i]
                ];
            }

            this.items = response.data;
        });
    }
},

When passing props to the child component, it works fine but may be affected by the nature of the asynchronous GET request:

<div class="items-container" v-for="category in categories" :key="category.name">
    <router-link :to="'category.link'" class="category-names-home-link">
        <h2 class="category-names-home">{{ category.name }}</h2>
    </router-link>
    <router-link :to="'category.link'" class="home-view-all" @mouseover.native="expand" @mouseout.native="revert">View All...</router-link>
    <div class="items">
        <!-- Pass to child component as props: -->
        <SubItem :item="categories.items" />
        <SubItem :item="categories.items" />
    </div>
</div>

Answer №1

  • Keep the items separate from the categories instead of adding them to the categories
  • To streamline, use a single computed object hash to hold all the filtered sets:
computed: {
  filtered() {
    if (!this.items) return null;
    const filtered = {};
    this.items.forEach(item => {
      if (filtered[item.category]) {
        filtered[item.category].push(item);
      } else {
        filtered[item.category] = [item];
      }
    });
    return filtered;
  }
}

Result:

{
'Glass': [ ... ],
'Ceramic': [ ... ]
...
}

In the template:

<div>
   <div v-for="category in categories" :key="category.name">
      <div class="items" v-for="item in filtered[category.name]">
         <SubItem :item="item" />
      </div>
   </div>
</div>

To ensure data is loaded before displaying anything, you can use v-if in the parent component:

<display v-if="items" :items="items"></display>

Take a look at this demo

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

Once chosen, zoom in on the map to view the results

I am facing an issue with multiple selects in my code, where one select depends on the result of another. The ultimate goal is to zoom in on the area that has been searched and found, but unfortunately, it is not functioning as expected. If you'd lik ...

Trouble with tab switching across multiple cards

I have been working on an app that generates multiple cards with 3 tabs on each card. However, I am facing an issue with tab switching. The tab switching works fine on the first card, but when I try to switch tabs on other cards, it still affects the tabs ...

How can I assign a unique background color to each individual column within a RadioButtonList?

I have an issue with setting 3 repeated columns. I want to assign different background colors to each of them. If you have any ideas on how I can achieve this, please share. Here is the code for my RadioButtonList: <asp:RadioButtonList ID="rblTimeSlot ...

Check to see if two sets of coordinates fall within the specified radius

I'm currently working on analyzing the collision data for major intersections in my city by aggregating it with the location information. My main goal is to determine the number of accidents that occurred within a 20-meter radius of each intersection. ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

Unable to save a string value from a function to MongoDB is unsuccessful

I've hit a roadblock. Working tirelessly to solve a persistent bug, but it feels like I'm getting nowhere. What am I missing? My goal is clear - once the user submits a form with the enctype of "multipart/form-data", I want to extract t ...

Tips on coding javascript within an MVC4 C# environment

I am currently working with MVC 4 and facing an issue where I have the same action name for multiple views. This makes it difficult to write JavaScript code in all pages individually. Can I simply write the JavaScript in the C# action result instead? I at ...

Vue version 3 is encountering an issue with a module that does not have an exported member in the specified path of "../../node_modules/vue/dist/vue"

After I updated my npm packages, errors started popping up in some of the imports from the 'vue' module: TS2305: Module '"../../node_modules/vue/dist/vue"' has no exported member 'X' The X instances affected inclu ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

methods for extracting json data from the dom with the help of vue js

Can anyone help me with accessing JSON data in the DOM using Vue.js? Here is my script tag: <script> import axios from "axios"; export default { components: {}, data() { return { responseObject: "" }; }, asy ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

Is there a method to track the number of active onSnapshot listeners from Firestore in my application?

In my app, I am implementing a feature that dynamically removes query onSnapshot listeners and replaces them with new ones. To ensure that resources are properly freed up, I need to test the effectiveness of the unsubscribe function. Unfortunately, I do n ...

What could be causing the Quasar drawer to overlap the Quasar toolbar in a Vue application?

I am currently utilizing the quasar UI framework and have a main layout file that includes only a toolbar. This toolbar is meant to display across all pages in my application. <template> <q-layout view="hHh Lpr lff" style="backgro ...

Issues with the plugin for resizing text to fit the parent div's scale

I've spent the last hour attempting to get this script to function properly, but no luck yet. Check out the correct jsfiddle example here: http://jsfiddle.net/zachleat/WzN6d/ My website where the malfunctioning code resides can be found here: I&apo ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Saving a Coordinated Universal Time and showcasing it in the corresponding local timezone

In my upcoming MVC4 application that will have a global audience, one of the features involves recording the date and time when a transaction is added or modified. Since I am storing the transaction datetime in UTC format, what would be the most effective ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Inject CSS into an iframe containing a JavaScript form by iterating over a collection of iframes

My task is to manipulate an iframe (chatbox) once it's loaded on a webpage. This chatbox consists of four iframes, each with a different id that changes with every page load. Since the iframe that needs manipulation is always the last one in the list, ...