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

What is the proper way to utilize a filtered object based on its properties within an Angular controller?

Currently, I am working on developing a stacked graph along with its associated table. To retrieve the necessary JSON data, I am utilizing $http.get() and then assigning it to $scope.dataset. Here's a snippet of the HTML: <input ng-model="_search ...

Invoking a .js file within an UpdatePanel from the CodeBehind

I have been dedicating my time to self-teach ASP.NET and JavaScript for a project, and I've hit a roadblock that has consumed dozens of hours. After discovering a fantastic drag-and-drop JavaScript list online, I copied the provided source code and o ...

Skipping the configuration file during the process of converting Node.js files to an executable using pkg

I am currently working on a node.js application and in order to prevent users from reading the code, I am attempting to convert my JavaScript files to executable files. I have been using the pkg module for this task, but I have encountered an issue. The p ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

Please restrict all scores to only one decimal point and ensure that all integer scores include a ".0" at the end, except for scores of 10 or 0

Ensure scores are rounded to a single decimal point and update all integer values with .0, except for 10 and 0. For example: 0.972 should be 0.9 2.83 should be 2.8 All integer scores will be updated as: 0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 I have ...

Conceal / reveal with jQuery

I am attempting to hide all divs and only display those connected with the "button" class. However, I'm encountering an issue where only the last div is visible, regardless of which div/button was clicked. EDIT: Here is the complete HTML code: < ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

"Utilizing Axios to convey JSON data into Vue Js: A Step-by-Step Guide

After saving my JSON data in a JS file for Vue, I encountered an issue with accessing it and getting my HTML v-for condition to work properly. The method described in the Vue.js documentation didn't help me fetch and execute the JSON data. Could someo ...

Transferring a list from MVC ViewBag to JavaScript

I have a situation where I am passing a list of users from my controller to the view using the ViewBag. Now, I also need to pass this same list to the JavaScript on the page. One way I thought of doing this is by iterating through the list with a foreach l ...

What's the most effective method for implementing a stylesheet through Javascript in a style switcher?

I've been tackling the challenge of creating a style switcher for my website. Through utilizing .append() and if and else statements, I managed to make it work successfully. Take a look at the code below: HTML <select name="active_style" id="lol" ...

Create a hover effect on HTML map area using CSS

Is it possible to change the background color of an image map area on hover and click without using any third-party plugins? I attempted the following code: $(document).on('click', '.states', function(){ $(this).css("backgro ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Upload file via AJAX immediately after downloading it (no need for storage)

Currently, I am in the process of developing a JavaScript script to safeguard an old game development sandbox website from being discarded by its owners. In order to prevent the loss of all the games on the site, I have managed to create a script that allo ...

Replacing an array element by a specific index number in a React application

I am dealing with an array of [false,true,false,false,true] and I am looking to update the boolean values based on their index numbers. I have been trying to solve this problem in react, but haven't found a workable solution yet. this.setState({ ...

Determining age in a Class upon instance creation

Is there a way to encapsulate the age calculation function within the Member Class without resorting to global space? I want to automatically calculate and set an age when creating an instance. Currently, I have a function that works, but I'm curious ...

VuexFire Transformations

Can someone shed some light on the mysterious mutations: VuexFire.mutations line in this code snippet for Vuex v2? I'm a bit confused about where my actual mutations should go. Currently using Vuex v1 and everything seems fine, but considering an upgr ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...