Struggling to properly send props to the child component in Vue 3

Is there a way to pass data from the request through axios in the root component to the child using Vue? Currently, only the "title" field is displayed correctly, but I also need to output the "body".

Note: This is my first time working with Vue and I'm seeking guidance on how to accomplish this correctly.

App.vue

<template>
    <app-news
    v-for="item in news"
    :key="item.id"
    :title="item.title"
    :id="item.id"
    :body="item.body"
    >
    </app-news>
</template>

export default {
  data () {
    return {
      news: []
}
  mounted() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts?_start=0&_limit=5')
      .then((resp) =>
        this.news = resp.data
      )
  },
  provide () {
    return {
      title: 'List of all news:',
      news: this.news
    }
  },

AppNews.vue

<template>
    <div>
            <hr/>
            <p v-for="item in news" :key="item.id">{{ item.body }}</p> // Need to pass here body content of the response from json
    </div>
</template>
     props: {
        news: [], // -> The issue might be here, I need to receive the response as a prop and validate it as well, as shown below
          title: {
            type: String,
            required: true
          },
          id: {
            type: Number,
            required: true
          },
          body: {
            type: String,
            required: true
          },
        }
      },

Answer №1

When using :title="item.title", :id="item.id", and :body="item.body" as props, you can directly access these variables without needing any additional props.


<template>
    <div>
          {{title}} <br/> {{body}} <br/> {{id}}
    </div>
</template>

props: {
   title: {
     type: String,
     required: true
   },
   id: {
     type: Number,
     required: true
   },
   body: {
     type: String,
     required: true
   },
}

Answer №2

If you're looking to implement the code snippet below:

const app = Vue.createApp({
  data() {
    return {
      articles: []
    }
  },
  async mounted() {
    const articles = await axios
      .get('https://jsonplaceholder.typicode.com/posts?_start=0&_limit=5')
     this.articles = articles.data
  },
})
app.component('appArticle', {
  template: `
    <div>
      <hr/>
      <p><b>{{ title }}<b></p>
      <p>{{ body }}</p> 
    </div>
  `,
  props: {
    title: {
      type: String,
      required: true
    },
    id: {
      type: Number,
      required: true
    },
    body: {
      type: String,
      required: true
    },
  }
})
app.mount('#demo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.1.3/axios.min.js" integrity="sha512-0qU9M9jfqPw6FKkPafM3gy2CBAvUWnYVOfNPDYKVuRTel1PrciTj+a9P3loJB+j0QmN2Y0JYQmkBBS8W+mbezg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
   <app-article
      v-for="item in articles"
      :key="item.id"
      :title="item.title"
      :id="item.id"
      :body="item.body"
      >
    </app-article>
</div>

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

Zurb Foundation's sections have a strange issue where navigating between them introduces unexpected whitespace

I'm feeling frustrated as I try to work with Zurb Foundation sections. I've updated to the latest version 4.3.1. Following the documentation provided here: but encountering strange behavior while navigating through results. Refer to the screen ...

Creating a simulated class within a function utilizing Jest

Currently, I am in the process of testing a controller that utilizes a class which functions like a Model. const getAllProductInfo = (request, response) => { const productInformation = new ProductModel().getAll(); response.status(200) resp ...

Achieving checked checkboxes based on already selected values in AngularJS

function Test1Controller($scope) { var storeid = window.localStorage.getItem("storeid"); var serverData = ["Samsung Galaxy Note", "Samsung Galaxy S6", "Samsung Galaxy Avant","Samsung Galaxy Young"]; $scope.items= [] ; var selectedvalue="Samsu ...

View is unable to trigger the success attribute

Currently, I am delving deep into Backbone JS and facing an issue where the 'success' function in 'EditUser' is not being triggered. I would greatly appreciate it if someone could guide me on what changes I need to make in the code? B ...

Performing a deep insert in SAPUI5 with the Kapsel Offline App on an OData V2 Model

Query: What is the process for performing a "Deep Insert" from a SAPUI5 Client application on an OData V2 Model? Situation: In my SAPUI5 Client application, I need to Deep Insert an "Operation" along with some "Components" into my OData V2 Model. // h ...

Unable to retrieve Google Maps route on Android device

After discovering the route between two latitude and longitude values on Google Maps using "Get Directions," everything appears accurately. However, when attempting to use the same directions in an Android mobile application, only the destination marker ...

Error encountered when attempting to embed a SoundCloud player in Angular 4: Unable to execute 'createPattern' on 'CanvasRenderingContext2D' due to the canvas width being 0

I attempted to integrate the SoundCloud iframe into my Angular 4 component, but encountered the following error message: Failed to execute 'createPattern' on 'CanvasRenderingContext2D': The canvas width is 0. Here is the iframe code ...

The choice between using "npm install" and "npm install -g" for

New to the world of node, and feeling a bit lost when it comes to all this "install" stuff. Could someone clarify for me, what sets apart install from install -g? If something is installed with install -g, can it be accessed from anywhere, or is it restr ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

Retrieve the data stored in a selection of checkbox fields on a form

I have a table of checkboxes: <div> <h1 class="text-center">Select activities</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Link activ ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Retrieve distinct values for the keys from an object array in JavaScript

Here is the structure of my array: const arr1 = [ { "Param1": "20", "Param2": ""8", "Param3": "11", "Param4": "4", "Param5": "18", ...

Can I safely execute JSON.parse() on the window's location hash?

Is it safe to store JavaScript variables in the URL's hash for web application state restoration through bookmarks? I've been considering using JSON serialization as a method. Storing variables like this: var params = { var1: window.val1, var2: ...

Creating synchronous automation in Selenium: A step-by-step guide

I am feeling increasingly frustrated at the moment and I am hoping to seek assistance on stackexchange. First and foremost, I must admit that I am not a seasoned Javascript developer, probably not even an experienced developer overall, but I do have some ...

difficulty using workbox to cache content in vue-cli

In my development setup with vue-cli v3.0.0.beta10 and the default integrated workbox, I included this configuration in my vue.config.js file (located in the root folder): pwa: { //pwa configs... workboxOptions: { // ...other Wor ...

The animation of a cube rotating to a different face is not functioning properly when using three.js

Why is my cube not animating when rotating to another face with the code below? How can I resolve this issue? new Vue({ el: '#app', data () { return { camera: null, scene: null, renderer: null, mesh: null, ...

Two identical Vue component instances

Is there a way to duplicate a Vue component instance after mounting it with new DOM? I am currently working on coding a template builder and I need to clone some blocks. Similar to the duplicate feature on this website ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Creating an interactive table with the power of FPDF and PHP

I have developed a unique Invoice System that allows users to customize the number of headings and fields using FPDF in conjunction with PHP. Subsequently, I can input the heading names and field values into HTML input fields. However, I am encountering a ...