Navigating through the pages with Nuxt and Vuejs proved to be quite the challenge

I'm currently in the process of developing a static blog project that fetches data from the WordPress REST API.

My objective is to showcase the article page upon clicking the title on the index file.

I require a customized route based on the post's slug.

However, I encounter a message stating "This page could not be found."

The event information for the changed route:

https://i.sstatic.net/EQYx5.png

Layout

pages
--| article
----| _slug.vue
--| index.vue

index.vue

<template>
  <div class="container">
    <h1>Blog</h1>
    <ul>
      <li v-for="article in posts" :key="article.id">
        <nuxt-link :to="{ name: 'article-slug', params: {slug : article.slug} }">{{ article.title.rendered }}</nuxt-link>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  asyncData({ req, params }) {
    return axios.get('https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/')
      .then((res) => {
        return { posts: res.data.slice(0, 5) }
      })
  },
  head: {
    title: 'List of posts'
  }
}
</script>

_slug.vue

<template>
    <div>
        <h1>
            {{ title.rendered }}
        </h1>
        <template>
          {{ content.rendered }}
        </template>
        <p><nuxt-link to="/">Back to home page</nuxt-link></p>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  validate({ params }) {
    return !isNaN(+params.slug)
    console.log(params)
  },
  async asyncData({ params, error }) {
    try {
      const { data } = await axios.get(`https://dev.lesdeuxvagues.com/api/wp-json/wp/v2/posts/?slug=${+params.slug}`)
      return data
    } catch (e) {
      error({ message: 'User not found', statusCode: 404 })
    }
  }
}

router.js

export function createRouter () {
  return new Router({
    mode: 'history',
    base: '/',
    linkActiveClass: 'nuxt-link-active',
    linkExactActiveClass: 'nuxt-link-exact-active',
    scrollBehavior,
    routes: [
        {
            path: "/article/:slug?",
            component: _540807ba,
            name: "article-slug"
        },
        {
            path: "/",
            component: _ac3e7d78,
            name: "index"
        }
    ],


    fallback: false
  })
}

Thank you for lending your assistance.

Answer №1

Ah, now I understand. My goal was to verify if a certain value is NaN.

Issue resolved successfully.

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 process for extracting the "user_id" from the token payload and inserting it into the JSON POST form in Django REST with SimpleJWT and Vue3?

After storing access and refresh tokens in my local storage, I have decoded the access token and found the "user_id" in the payload. However, I am struggling to comprehend how to include this "user_id" in a POST request to the REST API. Is it retrieved fro ...

How do I send a post request in MySQL that includes foreign keys?

I am working on creating a post request to verify if the user making the request is the same as the logged-in user and then posting the response. The setup involves having separate tables for customers and addresses, where I aim to link the customer ID wit ...

Generate a fresh array using the data from the existing array object

I have nested objects within arrays that I need to manipulate. { "page": [ { "num": "1", "comp": [ { "foo": "bar", "bar": "foo", ...

Tracker.autorun subscription triggers repeated firing of publish callback

Working on a ReactJS and Meteor project, I encountered an unexpected behavior that I would like to discuss here: Within the code, there is a block with Tracker.autorun containing a call to Meteor.subscribe. On the server side, there is a corresponding Met ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

Error encountered in VUE JS 3: The function vue.initDirectivesForSSR is not recognized as a valid function

I've been encountering some errors while trying to build my Vue web app with this configuration. I have searched for a solution, but couldn't find anyone facing the same issue as me. Any suggestions on how to resolve this problem? The build was s ...

Error: Unable to execute state.productDetails as a function

import React, { useEffect } from "react"; import Loader from "../layout/Loader"; import { useAlert } from "react-alert"; import { useDispatch, useSelector } from "react-redux"; import { getProductDetails, cle ...

Using v-model to control both form fields and populate dropdown menus

Looking to achieve two tasks using a v-select with dynamically loading items: 1. Need to connect item-text with form for insertion. 2. Trying to retrieve item-id upon selecting an option. Here is the code snippet: <v-select :items="t ...

Configuring Angular 6+ Applications at Run Time

What is the most effective approach for loading environment-specific configuration at runtime in an Angular application? The Angular documentation suggests utilizing APP_INITIALIZER, but this may not be early enough in the loading process for configuring i ...

What is the syntax for accessing a dictionary item within a <span> tag using JavaScript?

I'm working on a new functionality for a website that involves using a dictionary to store information about clubs, events, and times. var clubName = {}; var event = {}; var time = {}; var dict = new Map(); dict.set(clubName, "G ...

Tips for resolving the error that arises while attempting to create a React app

Encountered npm error code EACCES while trying to access /usr/local/lib. Permission was denied by the operating system due to inadequate user permissions. To resolve this, ensure you have the necessary write access to the specified directory and its parent ...

What is the best way to locate all complete words within a string, up to 65 characters in length?

Looking to enhance my titles for better Google SEO (using title tag in html). My product titles are currently 3-4 lines long and do not look appealing. I am looking for a way to identify the last complete word before the 65th character in a string. For e ...

Troubleshooting the issue of Ajax POST not properly sending the model data to the controller in ASP.NET Core

I've been attempting to send POST data to my controller from a Kendo dialog event, but I keep encountering the issue of the model being null. Despite trying multiple solutions mentioned on StackOverflow, none have proven effective. Here is my Ajax ca ...

Parsing JSON data to extract values stored in a two-dimensional array

In order to develop a basic version of Tic Tac Toe, I decided to store game data in a JSON file. Here is an example of how the file is structured: [ { "turn": "x", "board": [ [ " ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

Utilize the jQuery live() function on a single element

Looking for a solution to an issue with my Facebook-Like Chat on . Currently, the chat opens multiple bars when clicked, but only closes all at once. How can I make it so that each chat bar opens and closes individually when clicked? Any help would be ap ...

Can I safely temporarily overwrite a prototype method in a route handler in express?

I'm currently facing a scenario where I have an object containing numerous instances of the Date data type. This object is then converted into JSON format and returned as follows: router.post('/', function () { // Some code that retur ...

transform the stationary drawing to the top and left position at coordinate (0,0)

Exploring canvas has led me to encounter a puzzling issue with the translate method. While working on this fiddle http://jsfiddle.net/claireC/ZJdus/4/, my goal was to have the drawing move and bounce off all four walls. However, I noticed that it would no ...

Using Vue 3 to send formdata with axios

I've been attempting to upload images to a backend expressjs API using Vue 3. I'm creating a FormData object named "files" and sending it via axios to the server. However, the server isn't receiving anything (req.files is undefined). The ser ...