Troubleshooting Vue.js 2 Routing Issues: Difficulty Accessing Posts Variable

My first venture into Vue.js involves working with WP REST API.

Initially, all my posts are displayed perfectly. However, when I attempt to integrate Vue-router, the component responsible for showcasing all the posts, 'home-post-list', breaks down at the very first 'v-if="posts"' statement.

Evidently, Vue perceives that there are no posts and therefore does not render anything further. Unfortunately, I am unable to resolve how to make it acknowledge the presence of 'posts'. No errors appear in the console.

Upon inspecting Vue DevTools, I notice:

Hence, the 'router-view' seems to be functioning correctly, but the props are empty. Although I believed I was passing props from the main instance to the child component, it appears I may have made an error somewhere.

I will now showcase my existing code.

***HomePostList component

const HomePostList = Vue.component('home-post-list', {
  props:['posts'],
  template: `<div class="cell medium-8">
                        <div id="all-posts" class="all-posts" v-if="posts">
                        <div class="grid-x grid-margin-x">
                          <div class="post medium-6 cell" :class="{'medium-12':index===0}" v-for="(post,index) in posts">
                         <!-- rest of the component structure unchanged -->
                    </div>
                  </div>
});

***SinglePost Component

const SinglePost = Vue.component('single-post-template', {
  props:['posts'],
  template: `<div class="cell medium-8">
                    <div class="grid-x grid-margin-x">
                        <p>Single Post here</p>
                    </div>
                  </div>`
});

***Routes & Vue Instance

const routes = [
  {
        path: '/',
        component: HomePostList,
        props: true
  },
  { 
        path: '/post/:postId',
        name: 'post',
        component: SinglePost
  }
];

const router = new VueRouter({
  routes
});

new Vue({
// remaining copied code is left out intentionally for brevity
});

***index.php

<?php
/*
Template Name: Front
*/
get_header(); ?>

<!-- Home Page -->
<div class="grid-container">
  <div class="grid-x grid-margin-x">

    <!-- Main Post Container -->
    <router-view></router-view>

    <!-- Sidebar -->
    <div id="sidebar" class="cell medium-4">
      <sidebar-search></sidebar-search>
    </div>
  </div>
</div>

<?php get_footer();

Answer №1

After some trial and error, I found a solution by inserting posts into the router-view component.

<router-view :posts="posts"></router-view>

I'm not entirely sure if this is the most conventional method, but it did the trick for me.

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

One way to extract data from a Quasar table row using the @row-click event

Is it possible to retrieve the data associated with a row from a table using the @row-click event? How can I specifically access the id and name values of the row that was clicked in the example below? <q-table title="Treats" dense :dat ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

The issue with Webpack chunking is that no content is appearing because the chunks are not

For the past day, I've been trying to resolve a frustrating yet seemingly simple problem. My goal is to split my bundle.js file into chunks to enhance website loading speed. Below is my webpack.config file: module.exports = { devServer: { historyApi ...

Adjust the height to match the shortest sibling child div height

In my layout, I have multiple rows with each row containing multiple columns. Within each column, there is a div and a paragraph - the div contains an image. My goal is to set the div with the class cover-bg to the lowest height of cover-bg in the same row ...

Creating trails by following the cursor's movement in KineticJS

Currently, I am working on a drawing application using KineticJS. While I have successfully used it to draw shapes and straight lines by following the method outlined in KineticJS - Drawing Lines with Mouse, I now need to draw a line along the mouse's ...

Download an image file directly from an HTTP response in Laravel using Vue, Axios, and Intervention Image

Currently, I am in the process of setting up a media asset database by utilizing Laravel, Vue, Axios, and Intervention image. One of my main objectives is to allow the user to specify their desired image height and width before proceeding with the download ...

Joining Two Texts in HTML with a Link Embedded within

Within my HTML code, I have two specific strings: "Forgotten your password?" and "Please" 'HPERLINK' "to change your password". To manage these strings efficiently in different languages, I utilize a messageBundle file to store constants. This f ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

Nuxt sends a POST request to Laravel Sanctum which ultimately redirects to the login page

I have spent countless hours debugging and searching online with no success. My setup includes Laravel 8 with the Sanctum package, along with the latest Nuxt version as the front-end. I have successfully implemented GET requests on a couple of endpoints. H ...

Retrieve the specific data from the database when the <tr> element is hovered over

Hey everyone, I've been struggling with a problem for some time now. I have a loop that retrieves values from a database and I want each value to display onmouseover using JavaScript. However, it's only showing the value of the first row for all ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

What is the best way to create an `isHook` function in my code?

Is there a way to determine if a function passed is a React Hook? isHook(useState); // returns true isHook(() => {}); // returns false; I am looking for a method to distinguish whether a function attached to an object property is a hook or not. In cas ...

Obtain an identifier to be used as dynamic data in an ajax request with jQuery

I am struggling to extract the id from links that trigger the same ajax function. I have over 30 links generated dynamically, as shown below: <a href="javascript:void(0)" id="105">Item 105</a> <a href="javascript:void(0)" id="379">Item 3 ...

How to set a canvas as the background of a div element

Check out my code snippet below: <!DOCTYPE html> <html> <body> <div id='rect' style='width:200px;height:200px;border:1px solid red'> </div> <canvas id="myCanvas" style="borde ...

Encountering a Firebase error: createUser failed due to missing "password" key in the first argument in AngularJS

Recently, I started learning Angular and decided to follow an online tutorial on creating a chat application. However, I encountered an issue when trying to register with an email and password - the error message "Firebase.createUser failed: First argument ...

What could be causing the issue with the Vue CLI not working after installation via npm 6.9.0?

Whenever I try to run the command below: vue create hello-world I receive this message : 'vue' is not recognized as an internal or external command, operable program or batch file. It's been a month and I'm still struggling to fin ...

vue-loader: The specified module could not be located

I'm stuck trying to solve the issue with the module not found error. This module is relative and cannot be located: ./graphics/logo.svg in ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIden ...

Embedded Twitter posts are not showing up correctly when using vue

My backend is Django and frontend is Vue. In one of my models, I have a rich text editor. When saving the content, it converts tweet links to embedded HTML tweets. While displaying this content in a div with v-html binding in Vue, everything appears as exp ...

Obtain an array as the response from an Ajax call

When passing data using Ajax request, I utilize the code below: var query = { "username" : $('#username').val(), "email" : $('#email').val(), } $.ajax({ type : "POST", url : "system/process_registration.php", ...