Looking for assistance in managing arrays and improving axios response handling

I currently have a structure like /url/{category}.

Below is the code snippet used to fetch and display some of these on the main page:

export default {
    data() {
        return {
            topnews:[],
            newsfive:[],
            categories: { 
                tshirts:'',
                shirts:'',
                shoes:'',
                useful:'', 
            }
        }
    },
    methods() {
        async getAll(){
            axios.all([
                axios.get(`/topnews`),
                axios.get(`/news`),
                axios.get(`/tshirts`),
                axios.get(`/shirts`),
                axios.get(`/shoes`),
                axios.get(`/useful`)])
                .then(axios.spread((topnews, news, tshirts, shirts, shoes, useful) => {
                    news.data.length = 5;
                    tshirts.data.length = 5
                    shirts.data.length = 5
                    shoes.data.length = 5
                    useful.data.length = 5

                    this.newsfive = news.data;
                    this.topnews = topnews.data;

                    this.categories = {
                        tshirts: tshirts.data,
                        shirts: shirts.data,
                        shoes: shoes.data,
                        useful: useful.data,
                    }
                })).catch(error => console.log(error))
        }
    }
    created()  {
        this.getAll() 
    }
}

The functionality works as intended. However, when changing the route to /tshirts and navigating back to the main page using the browser, an error message is displayed:

typeerror content read-only property

In addition, I am looking for a way to streamline the rendering process by combining the different items into a single array instead of having separate div elements:

<div v-for="tshirts,key in categories.tshirts" :key="categories.tshirts.slug">
    <img :src="tshirts.thumb" class="img-responsive" width=100%/>
    <p>{{tshirts.title}}</p>
</div>

Is it feasible to create a filtered computed response from the axios call and then render a single div element for all items?

<div v-for="item,key in categories(tshirts)" :key="categories(item.slug)">

Additionally, how can I limit the size of the axios response array?

Answer №1

Implement the Category.vue component to display category-specific content

<template>
  <div v-for="(item, key) in category" :key="item.slug">
      <img :src="item.thumb" class="img-responsive" width=100% />
      <p>{{ item.title }}</p>
  </div>
</template>
<script>
export default {
    data() {
        return {
            category: { }
        }
    },
    methods() {
        getCategory() {
          axios.get(`/${this.$route.params.category}`)                
               .then((response) => {
                  this.category = response.data.slice(0, 5);                    
               }).catch(error => console.log(error));
        }
    }
    created()  {
        this.getCategory() 
    }
}
</script>

In your App.vue, include router-link elements for each category

<template>
   <nav>
      <router-link to="{ name: 'category', params: {category: 'tshirts'} }">T-Shirts</router-link>
      <router-link to="{ name: 'category', params: {category: 'shirts'} }">Shirts</router-link>
     <!-- add more categories here -->
   </nav>
   <main>
      <router-view></router-view>
   </main
</template>

Ensure you have included the vue-router library

import Category from "./Category.vue"

routes = [
  {
    name: "category",
    path: "/:categoryId",
    component: Category
  }
]

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

Having issues with my custom AngularJS directive functionality

app.directive("myData", function() { return { templateUrl: '/my-data.html' }; }); my-data.html file code <tr ng-repeat="employee in employees"> <td>{{employee.id}}</td> <td>{{employee.name}}</t ...

Eliminate unseen and unique characters in Java or JavaScript

I am looking to eliminate the [LS], [LS] character that only shows up when pasted in Notepad++. This data was inserted in a way that it is hidden and can only be seen on a UTF-8 encoding editor. Additionally, I want to remove characters like phone; email; ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

Issue with modal rendering in Bootstrap4 when the body is zoomed in

I am encountering an issue with a Bootstrap html page where the body is zoomed in at 90%. The Bootstrap modal is displaying extra spaces on the right and bottom. To showcase this problem, I have created a simple html page with the modal and body set to 90% ...

Is jQuery automatically loaded in laravel 6? I keep encountering an uncaught type error

Everything was going smoothly with my project until I added authentication. Following the documentation here, I used composer to require laravel/ui and then did php artisan ui vue --auth. Prior to implementing authentication, the scripts were loading corr ...

Using jQuery Datepicker, showcase two distinct datepickers on a single page

Currently, I am utilizing the jQuery [Datepicker][1] on a website, but I am facing challenges when attempting to display two datepickers on the same page in different manners. The first one should only appear once you click the text box, and once a date i ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

Executing a PHP function within a Laravel controller using Ajax

In my Laravel project, I have a Controller named Clientecontroller that is working perfectly. It contains a method called listar() which retrieves client information. public function listar(Cliente $cliente) { $clientes = DB::table('clientes' ...

Issue occurs when nested functions prevent the data() variable from updating

As a newcomer to VUE, I may not be using the right terminology so bear with me. I'm attempting to update a variable that is defined in the script tag's "data()" function. The issue arises when trying to change the value of a variable within the ...

To install the Vue CLI globally, simply type 'npm install -g @vue/cli'. Keep an eye out for any warnings or

When I run the command npm install -g @vue/cli, changed 851 packages, and audited 852 packages in 2m 64 packages are looking for funding 4 vulnerabilities (2 moderate, 2 high) To address all issues (including breaking changes), run: npm audit fix --fo ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...

What is the best way to combine node-sass and sass-autoprefixer in a project?

I'm struggling to implement the code in my package.json. Here is the code snippet: { "name": "nodesass", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "node-sass": "^4.11.0" }, "devDependencies": ...

Failed to locate lodash during npm installation

I recently set up my project by installing lodash and a few other libraries using npm: npm install grunt-contrib-jshint --save-dev npm install grunt-contrib-testem --save-dev npm install sinon --save-dev npm install -g phantomjs npm install lodash --save ...

There seems to be an issue with the React Native FlatList: It appears that there is no overload matching this call and some

I am currently learning React Native and attempting to create a basic chat room application. I am facing an issue with the FlatList component that I can't seem to resolve. Even though I have provided both the data prop and renderItem prop to the FlatL ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

Update a row within an HTML table by incorporating PHP and JavaScript/jQuery, then store the changes within a database

I have a table populated with data from the database. I would like to be able to edit each row individually and save the changes back to the database. I did some research and found that this can be accomplished using JavaScript/jQuery, but I am unsure of ...

I am interested in extracting information from a public Facebook post

Is it possible to scrape or utilize the FB API to retrieve data from a public profile's wall post? By inspecting the element on the URL, you can see most of the data as well as the ajax calls for infinite scrolling on the wall. How could one go about ...

Concealing messages in React after a brief period

The task at hand involves making a message disappear after 5 seconds. In the following code snippet, I have a scenario where clicking on the "Generate Room Name" button will populate a URL in a text box. After copying this URL using the Copy button, a mes ...

My goal is to programmatically eliminate captcha from a website

Is there a way to automatically remove capture from a Page using javascript (Greasemonkey)? The page's HTML structure seems complex, so any suggestions on how to achieve this would be greatly appreciated. <div class="wrapper"> <d ...

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...