Bringing in More Blog Posts with VueJS

Exploring the Wordpress API and devising a fresh blog system. As a newbie to VueJS, I'm intrigued by how this is handled.

The initial blog posts load as follows:

let blogApiURL = 'https://element5.wpengine.com/wp-json/wp/v2/posts?_embed&per_page=12'

let authorApiURL = "https://element5.wpengine.com/wp-json/wp/v2/users"

let newPage = 1;

let posts = new Vue({

  el: '#app',

  data: {
    authors: null,
    currentAuthor: '23',
    posts: null,
    pageNumber: newPage,
    range: 0
  },

  created: function() {
    this.fetchAuthorData()
    this.fetchBlogData()
  },

  watch: {
    currentAuthor: 'fetchBlogData'
  },

  methods: {
    fetchAuthorData: function() {
      let xhr = new XMLHttpRequest()
      let self = this
      xhr.open('GET', authorApiURL)
      xhr.onload = function() {
        self.authors = JSON.parse(xhr.responseText)
      }
      xhr.send()
    },
    fetchBlogData: function() {
      let xhr = new XMLHttpRequest()
      let self = this
      xhr.open('GET', blogApiURL + '&page=' + self.pageNumber + '&author=' + self.currentAuthor)
      xhr.onload = function() {
        self.posts = JSON.parse(xhr.responseText)
      }
      xhr.send()
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dfbf8e8cdbfa3bda3be">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <div class="author-toggle-wrap post">
    <select v-model="currentAuthor" name="authors" id="author-select">
        <template v-for="author in authors">
            <option
              :id="author.id"
              :value="author.id"
              name="author.id">{{ author.name }}</option>
        </template>
      </select>
  </div>

  <div class="post-wrapper">
    <p>Current Author: <code>{{ currentAuthor }}</code></p>
    <template v-for="post in posts">
<div class="post">
<h2 class="post-title" v-html="post.title.rendered"></h2>
          <template v-if="post._embedded['wp:featuredmedia']">
            <a v-if="post._embedded['wp:featuredmedia'][0].media_details.sizes['large']" :href="post.link">
<img :src="post._embedded['wp:featuredmedia'][0].media_details.sizes['large'].source_url" />
</a>
          <a :href="post.link" v-else>
            <img src="https://element5.wpengine.com/wp-content/themes/wp-starter-theme/dist/images/default-thumb.jpg" />
          </a>
          </template>
    <div class="excerpt" v-if="post.excerpt.rendered" v-html="post.excerpt.rendered"></div>
    <div class="entry-meta" v-if="post._embedded.author[0]">
      <a class="author-wrap" :href="post._embedded.author[0].link"><img class="avatar" :src="post._embedded.author[0].avatar_urls['48']" />by&nbsp; {{ post._embedded.author[0].name }} </a>
      <a class="button read-more" :href="post.link">Read More &raquo;</a>
    </div>
  </div>
  </template>
</div>
</div>

Satisfied with the results! Vue has sparked my excitement and revealed great potential!

Attempting to figure out how to load more posts without wiping out existing ones. Started on this approach:

Vue.component('sub-blog', {
  template: '<div>On Each Click Load Next 12 posts here!</div>'
})

let newPosts = new Vue({
  el: '#load-more-posts',
  data: {
    range: 0
  },
  methods: {
    addMorePosts: function() {
      newPage++
      this.range += 1
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7919282a7d5c9d7c9d4">[email protected]</a>/dist/vue.js"></script>
<div id="load-more-posts">
  <sub-blog v-for="n in range"></sub-blog>
  <div class="load-more">
    <button v-on:click="addMorePosts" class="btn">Load More</button>
  </div>
</div>

After some tinkering, seeking guidance on loading dynamic data into the component correctly. It's adding new components upon click which is neat but requires firing off a new api GET request with an updated page number to append the same layout as initially loaded posts.

Check out the pen here: https://codepen.io/trafficdaddy/pen/YEwNKy?editors=1010

Appreciate any assistance!

Answer №1

Instead of creating a separate component for fetching more posts, you can simply implement it within the existing component. Check out this example: https://codepen.io/anon/pen/aVdpLb?editors=1010

addMorePosts: function(){
this.pageNumber += 1
this.range += 1
this.fetchBlogData();
}

All you need to do is keep the button in the same component and update the array with new posts fetched from the API.

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

MUI full screen dialog with material-table

Issue: When I click a button on my material-table, it opens a full-screen dialog. However, after closing the dialog, I am unable to interact with any other elements on the screen. The dialog's wrapper container seems to be blocking the entire screen. ...

Learn how to incorporate slide transitions into the dropdown menu of a navbar in Bootstrap 4, complete with Vue.js transition effects

I'm attempting to incorporate a slide up and down transition into the bootstrap 4 dropdown menus using vue transitions. Unfortunately, the transition isn't functioning as expected. Even after utilizing the transition element, the animation stil ...

iPhone height is not correct

One issue I faced was when trying to view a webpage in landscape mode on iPhones (specifically testing on model SE, but it appears that many people are experiencing the same problem with other iPhone models). I have created a simple example below, consist ...

Bookshelf.js has implemented a new feature where it automatically encrypts passwords with bcrypt every time data is updated

My User Model is var Bookshelf = require('../../db').bookshelf; var bcrypt = require('bcrypt'); var Promise = require('bluebird'); var Base = require('./../helpers/base'); // Custom user model var Custom_User_Mod ...

Error occurred due to missing dependency during file import

I'm attempting to include a new dependency within the script tag of a Vue.js Component. import AuthenticationService from '@/services/AuthenticationService.js' The error message that I am encountering states - This dependency was not foun ...

The updating of input and output does not happen instantly; there is a delay before changes

Having an issue with updating input values in React. When using the setState method, the console log does not show the updated input value immediately. For instance, typing "a n" into the input only logs "a" after the second keystroke... Although I under ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

How to effectively pass data between parent and child controllers in Angular 1 - Seeking guidance

Currently, I am working on two separate applications that have a common requirement of displaying active incidents and closed incidents. Both apps involve similar logic for creating, modifying, saving, and deleting incidents. I am exploring the best appro ...

Submitting form occurs upon selecting autocomplete suggestion

When a user fills out my form and hits the Go button or presses Enter, the form submits. However, when typing in the text box, it triggers an auto-complete feature after just one character. If the user uses arrow keys to navigate through the auto-complete ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

What is the process for assigning an item from the result list to the parent Div tag of the current object?

I've been working on a function to insert the number of Facebook Likes into a Div tag. The script I have so far can extract the URL from a Div tag inside another Div named 'entry'. Then, using the .getJSON() method, it fetches the Facebook l ...

Creating a Social Media Platform with JavaScript, Bootstrap, JQuery, PHP, and Mysqil

I am currently in the process of developing a social networking platform that will have similar features as Instagram. Users will be able to log in, create posts, leave comments, like content, share posts, and send data to a server for storage or display p ...

Encountering difficulty extracting information from an XML document within the Parse Cloud utilizing the XMLReader in an Express application

My goal is to extract elements from an XML file that I have already stored on the Parse Cloud for my Express app. I began coding after finding a helpful resource on using XMLReader with XPath on cloud code, as well as a guide on Parse httpRequest for retri ...

Encountered an error while trying to click the cookie button using Selenium: "object[] does not have a size or

I've been struggling to interact with a button inside a pop-up using Selenium, but I keep encountering this error: object [HTMLDivElement] has no size and location I initially tried to simply click the button since it is visible on the page and I wai ...

What is the best way to dynamically render classes based on conditions in a table using React Bootstrap?

I am looking for a way to dynamically change the color of a class based on the transaction data in a table. import React from "react"; import Table from "react-bootstrap/Table"; import "./TableComponent.css"; const TableComponent = ({ Movement }) =&g ...

"Utilize Regular Expressions to conceal part of a text string with a

Looking for a way to conceal part of a string using JavaScript? For example, wanting to mask the second and third segments of a credit card number like this using regex: 4567 6365 7987 3783 → 4567 **** **** 3783 3457 732837 82372 → 3457 ****** 82372 ...

Querying data from a label using jQuery

I am facing a challenge with reading label attributes in jQuery. I have multiple labels, each with the same class. These labels contain important information that I need to access. However, despite being able to select the object using $, I am struggling ...

What is the best way to show a nested div element within a v-for loop in Vue.js?

One interesting feature of my coding project is that I have an array nested within another array, and I iterate through them using two v-for loops. The challenge arises when I try to display a specific div in the second loop only upon clicking a button. ...