• Breaking News

    VUE TIP - Appending rows into DIV dynamically

    Let's suppose you want to display hundreds of rows into a DIV, but due to performance issues, you don't want to add them all at once.

    You can use VUE to address this kind of need very easily.


    Data Source

    In this use case, the data is being served as JSON from our backend. It will be an array of image URLs like this:

    { "images": 
      [
        "image1-url",
        "image2-url",
        .....
        "imageN"
      ]
    }
    


    Data View

    The data view will be composed in the following HTML DIV that represents a table row:

    <div class="row">
     <div class="col-6 col-sm-4 nopadding" v-for="index in recno" :key="index">
      <div class="embed-responsive embed-responsive-16by9">
       <img :src="images[index]" width="510" height="400" onclick="modal(this);"></img>
      </div>
     </div>
    </div>
    
    Tip 1: Here, we are using the V-FOR directive to render the JSON array but limiting the amount of data by a predefined value represented by the "recno" variable.

    Then, we will manipulate this view using a button that will trigger a custom VUE method called "loadmore". This method will evaluate how many items will be appended to the data view, basically to avoid adding blank items.

     <div class="row">
     <div class="col-6 col-sm-4 nopadding">
      <btn-group>
       <btn @click="loadmore">more photos</btn>
      </btn-group>
     </div>
    </div>
    
    Tip 2: The "loadmore" method will be our main data controller.

    The VUE method

    This is the full code needed, easy as pie:

    loadmore: function(event) {
      var tope = this.images.length ;
      if(this.recno + 12 <= tope) {
        this.recno += 12 ;
      } else {
        this.recno += tope - this.recno -1 ;
      }
    }
    
    The code logic is pretty straightforward: we will adding 12 items to the DIV verifying always to not exceed the length of our JSON array. The array lenght is represented by the "tope" variable.

    In case we need to add less than 12 items, the number of elements to add is adjusted accordingly.

    Complete Code

    You can grab the complete code from here: Live Web Application

    No comments