Creating a load more feature with Vue

Having some trouble implementing a load more button that adds 10 more items to the page when clicked. The button code seems to be causing issues as all items still appear on the page and there are no errors in the console either. As a result, the button is not functioning properly.

Furthermore, I am attempting to incorporate this functionality with a filter function. Any examples or assistance would be greatly appreciated.

data() {
        return {
            estates:[],
            moreEstates: [],
            moreEstFetched: false,
        }
},

mounted() {
        axios.get('/ajax').then((response) => {
            this.estates = response.data
            this.insertMarkers();

        });
},

methods: {
        handleButton: function () {
            if(!this.moreEstFetched){
                axios.get('/ajax').then((response) => {
                    this.moreEstates = response.data;
                    this.estates = this.moreEstates.splice(0, 10);
                    this.moreEstFetched = true;
                });
            }
            var nextEsts = this.moreEstFetched.splice(0, 10);
            
            this.estates.push(nextEsts);
        },
},

computed: {
        one: function () {
            let filteredStates = this.estates.filter((estate) => {
                return (this.keyword.length === 0 || estate.address.includes(this.keyword)) &&
                (this.rooms.length === 0 || this.rooms.includes(estate.rooms)) &&
                (this.regions.length === 0 || this.regions.includes(estate.region))});

                if(this.sortType == 'price') {
                    filteredStates = filteredStates.sort((prev, curr) => prev.price - curr.price);
                }
                if(this.sortType == 'created_at') {
                    filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
                }

                filteredStates = filteredStates.filter((estate) => { return estate.price <= this.slider.value});
                filteredStates = filteredStates.filter((estate) => { return estate.extend <= this.sliderX.value});
                filteredStates = filteredStates.filter((estate) => { return estate.m2_price <= this.sliderT.value});

                return filteredStates;
        },
},
<table class="table table-hover">
    <thead>
        <tr style="background-color: #fff ">
            <th scope="col">イメージ</th>
            <th style="width:175px;"scope="col">物件名</th>
            <th style="width:175px;"scope="col">住所</th>
            <th scope="col">販売価格</th>
            <th scope="col">間取り</th>
            <th scope="col">専有面積</th>
            <th scope="col">坪単価</th>
            <th style="width:90px;" scope="col">物件詳細</th>
        </tr>
    </thead>

  <tbody>
        <tr  v-for="estate in one">
            <td><img id="image" :src="estate.image" alt=""></td>
            <td>{{estate.building_name}}</td>
            <td>{{estate.address}}</td>
            <td>{{priceSep(estate.price)}} 万円</td>
            <td>{{estate.rooms}}</td>
            <td>{{xtendSep(estate.extend)}} m²</td>
            <td>{{estate.m2_price}}</td>
            <td><a :href="/pages/+estate.id">物件詳細</a></td>
        </tr>
  </tbody>

</table>

<button class="btn btn-primary loadmorebutton" @click="handleButton">Load more</button>

Answer №1

In response to @pyriand3r's observation about the asynchronous nature of the axios request, you can utilize async/await in the following way without making significant modifications to the existing code.

methods: {
  handleButton: function () {
      if(!this.moreEstFetched){
           axios.get('/ajax').then(async (response) => {
              this.moreEstates = await response.data;
              this.estates = this.moreEstates.splice(0, 10);
              this.moreEstFetched = true;
          });
      }
// It is important to note that you cannot splice a boolean value, only arrays.
      var nextEsts = this.moreEstFetched.splice(0, 10);

      this.estates.push(nextEsts);
  },
},

Explore more about Async/Await in JavaScript

Answer №2

Implemented some modifications to your code, please review the comments for clarity.

However, these changes mirror those made in the previous post.

data() {
        return {
            visible:true ,
            estates:[],
            moreEstates: [],
            moreEstFetched: false,
            size: 10,
            selectedPage:0,
            init: false,
            
        }
},
updated: function () { // triggered only once upon loading
            if (!this.init) {
                this.handleButton();
                this.init = true;
            }
        },
mounted() {
// The axios call here should be removed to use handleButton solely for data retrieval
       // axios.get('/ajax').then((response) => {
        //    this.estates =this.filterData(response.data)
          //  this.insertMarkers();
          //  this.showMore();
     //   });
},

methods: {

        filterData: function (data) {
let filteredStates = data.filter((estate) => {
                return (this.keyword.length === 0 || estate.address.includes(this.keyword)) &&
                (this.rooms.length === 0 || this.rooms.includes(estate.rooms)) &&
                (this.regions.length === 0 || this.regions.includes(estate.region))});

                if(this.sortType == 'price') {
                    filteredStates = filteredStates.sort((prev, curr) => prev.price - curr.price);
                }
                if(this.sortType == 'created_at') {
                    filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
                }

                filteredStates = filteredStates.filter((estate) => { return estate.price <= this.slider.value});
                filteredStates = filteredStates.filter((estate) => { return estate.extend <= this.sliderX.value});
                filteredStates = filteredStates.filter((estate) => { return estate.m2_price <= this.sliderT.value});

return filteredStates;
        },
        showMore: function(){
                    if (Math.ceil( this.moreEstates.length / this.size) <= this.selectedPage +1 ){
            this.selectedPage++;
            
       // Use slice instead of splice as it's non-destructive
            var nextEsts = this.moreEstFetched.slice((this.selectedPage * this.size), this.size);
            
            this.estates.push(nextEsts);
           }else this.visible= true; // hide "Show More"
        
        },

        handleButton: function () {
            if(!this.moreEstFetched){
                axios.get('/ajax').then((response) => {
                    // Filter the entire dataset at once
                    this.moreEstates = this.filterData(response.data);
                    this.moreEstFetched = true;
                    // Relocated this line from elsewhere
                    this.insertMarkers(); 
                    this.showMore();
                });
            }else this.showMore();
        },
},
<table class="table table-hover">
    <thead>
        <tr style="background-color: #fff ">
            <th scope="col">イメージ</th>
            <th style="width:175px;"scope="col">物件名</th>
            <th style="width:175px;"scope="col">住所</th>
            <th scope="col">販売価格</th>
            <th scope="col">間取り</th>
            <th scope="col">専有面積</th>
            <th scope="col">坪単価</th>
            <th style="width:90px;" scope="col">物件詳細</th>
        </tr>
    </thead>
  <tbody>
        <tr v-for="estate in estates">
            <td><img id="image" :src="estate.image" alt=""></td>
            <td>{{estate.building_name}}</td>
            <td>{{estate.address}}</td>
            <td>{{priceSep(estate.price)}} 万円</td>
            <td>{{estate.rooms}}</td>
            <td>{{xtendSep(estate.extend)}} m²</td>
            <td>{{estate.m2_price}}</td>
            <td><a :href="/pages/+estate.id">物件詳細</a></td>
        </tr>
  </tbody>
</table>

<button v-if="visible" class="btn btn-primary loadmorebutton" @click="handleButton">Load more</button>

Answer №3

Frankly, I'm not entirely convinced that this is the optimal approach, but I opted for a much simpler method to accomplish it...

data() {
    return {
        moreEstates: 10,
    }
},
<table class="table table-hover>
  <tbody>
        <tr v-if="moreIndex < one.length"  v-for="moreIndex in moreEstates">
            <td><img id="image" :src="one[moreIndex].image" alt=""></td>
            <td>{{one[moreIndex].building_name}}</td>
            <td>{{one[moreIndex].address}}</td>
            <td>{{priceSep(one[moreIndex].price)}} million yen</td>
            <td>{{one[moreIndex].rooms}}</td>
            <td>{{xtendSep(one[moreIndex].extend)}} m²</td>
            <td>{{one[moreIndex].m2_price}}</td>
            <td><a :href="/pages/+one[moreIndex].id">Property Details</a></td>
        </tr>
  </tbody>
</table>

<button class="btn btn-primary loadmorebutton" @click="moreEstates += 10">View Next 10 Properties</button>

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

Tips for unit testing an Angular Service that is primarily responsible for redirecting to an external page from the application

My service is responsible for redirecting to a separate login page since we are implementing login as a service. function redirectToMembership() { var returnURL = $location.host(); returnURL+="/#/Authorization"; $window.location.href=Environme ...

Conceal an item upon deletion using the this.$http.delete() method

I'm trying to implement a feature on my VueJS frontend website where each deleted item is automatically hidden. In my store.js file, I have a property called eventIsActive which is initially set to true: export const store = new Vuex.Store({ state ...

Passport authentication leading to incorrect view redirection in Express

I'm struggling to understand why the URL is updating but leading to the incorrect view. Once a user is authenticated with passport, the URL changes to my code (/clients) but it redirects back to the homepage view. After authentication, I want the us ...

Show the GitHub repositories of the user within a React application

Even though I am relatively new to React, I managed to create a GitHub search application. In this app, you can input a user's name in a search box and view their avatar, bio, username, etc. However, I'm facing an issue with fetching their reposi ...

The Bootstrap Vue Pagination feature seems to be experiencing an issue where data is not being displayed on

My VueJS application utilizes Bootstrap Vue Table and Pagination components to display a list of users with pagination. Although the data is successfully loaded, page 2 of the pagination does not render any information. The Users component passes the nece ...

Choosing an option in react-select causes the page to unexpectedly shift

Encountering a problem with a mobile modal developed using react-select. The selectors are within a div with fixed height and overflow-y: scroll. Upon selecting an option for the 'Choose observer' select, the entire modal briefly jumps down in th ...

Next.js Refresh Screen

Is there a way to refresh my client's web page from the server at a specific time? I need the client's page to be refreshed at 12pm, and although I'm using a scheduler, it doesn't seem to be automatically refreshing the web page on the ...

Creating a connection between my .html and .ejs files: A step-by-step guide

I have successfully created a pair of HTML files - index.html & contact.html. Within these files, I have implemented a navigation bar that allows for seamless transition between them. Recently, I delved into the realm of retrieving APIs and crafted an app ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

Validation in Ajax Response

When receiving an object from my API call, I want to perform error checking before displaying the JSON data in my view. function response(oResponse) { if (oResponse && oResponse != null && typeof oResponse === "object" && oResponse.response ...

The transition property in CSS and JavaScript does not seem to be functioning properly in Firefox

Recently, I integrated a Slide in menu script on my website using a Slide in menu script. After following all the instructions provided, the menu started working flawlessly on Chrome and Safari browsers. However, my main goal was to make it function on Fir ...

Ways to get a Discord bot to echo a message?

As a novice in the world of discord.js and bot creation, I am eager to implement a simple magic 8-ball inspired command. This command will allow users to ask the bot a question and receive a random answer in response. const commands = [ new SlashCommandBui ...

Mastering the art of debugging VueJS using Chrome's powerful breakpoint tools

Currently I am a developer who primarily uses VIM, and I have been exploring ways to leverage chrome breakpoints for debugging in my Vue.js app. In addition, I am utilizing nuxt alongside Vue for app development. I am curious if anyone has successfully ma ...

Encountering a problem with Vue when running the node-rdkafka package

I added node-rdkafka to my project using the command npm install node-rdkafka. Then, I included it in my code like this: import Kafka from 'node-rdkafka'; created() { console.log(Kafka.features); } An error occurred when running npm r ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Error message: `$injector:modulerr - Angular JS` - Indicates an

Currently, I am trying to delve into the world of Angular JS by taking the codeschool course "Shaping up with angular js". The instructor in the videos emphasizes the importance of wrapping code in function(){}. However, upon attempting to do so, an error ...

Cross-Origin Resource Sharing (CORS) for HTML

Here is a code snippet I found on http://jakearchibald.com/scratch/alphavid/ $("#video").append('<video id="movie" style="display:none" autobuffer><source id="srcMp4" src="https://host-away-from-host.com/file.mp4" type=\'video/mp4; ...

Is there a way for me to direct to a different HTML page once I click on a certain data point?

At the moment, I have been utilizing this complete set of calendar codes. <!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <link href='fullcalendar.css' rel='stylesheet' /> <link href=&a ...

Custom value in Field for radio type in Redux form

Can anyone help me figure out how to input text into a radio field using Redux form? Here are the fields I am working with: <Field name={some.name1} value={'text1'} component={renderRadioElement} type="radio" /> <Field name= ...