Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components.

If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in using the same cid in one place (the parent) - is this achievable?

Both the parent and child components feature identical mounted and data functions. The cid is transmitted to the contentDeliveryUrl for data retrieval.

App.vue

<template>
  <div id="app" class="container" cid="7e4301de-9c6e-4fab-9e68-3031b94d662d">

    <Images cid="same as parent div" />

    <Video cid="same as parent div" />

    <TextType cid="same as parent div" />

    <Card cid="same as parent div" />

  </div>
</template>

<script>
  import axios from 'axios';
  import Images from "./components/Images";
  import Video from "./components/Video";
  import TextType from "./components/TextType";
  import Card from "./components/Card";

  export default {
    name: 'app',
    props: ["cid"],
    components: {
      Images,
      Video,
      TextType,
      Card
    },
    mounted() {
      axios({method: "GET", "url": this.contentDeliveryUrl}).then(result => {
          // eslint-disable-next-line
          this.content = amp.inlineContent(result.data)[0];
          console.log(this.content)
        }, error => {
          console.error(error);
        });
    },
    data() {
      return {
        contentDeliveryUrl: 'https://c1.adis.ws/cms/content/query?fullBodyObject=true&query=%7B%22sys.iri%22%3A%22http%3A%2F%2Fcontent.cms.amplience.com%2F${this.cid}%22%7D&scope=tree&store=testing',
        content: []
      }
    }
  }
</script>

Image.vue

<template>

<div v-if="content.image">

</div>

</template>

<script>
  import axios from 'axios';

  export default {
    props: ["cid"],
    name:'Images',

    mounted() {
      axios({method: "GET", "url": this.contentDeliveryUrl}).then(result => {
          // eslint-disable-next-line
          this.content = amp.inlineContent(result.data)[0];
          console.log(this.content)
        }, error => {
          console.error(error);
        });
    },
    data() {
      return {
        contentDeliveryUrl: 'https://c1.adis.ws/cms/content/query?fullBodyObject=true&query=%7B%22sys.iri%22%3A%22http%3A%2F%2Fcontent.cms.amplience.com%2F${this.cid}%22%7D&scope=tree&store=testing',
        content: []
      }
    },
}
</script>

All components display undefined data in Vue Devtools.

Answer №1

To enhance your component, introduce a new data property named cidItem and connect it to your props in the following manner:

<template>
  <div id="app" class="container" :cid="cidItem">

    <Images :cid="cidItem" />

    <Video :cid="cidItem"  />

    <TextType :cid="cidItem"  />

    <Card :cid="cidItem"  />

  </div>
</template>

<script>
  import axios from 'axios';
  import Images from "./components/Images";
  import Video from "./components/Video";
  import TextType from "./components/TextType";
  import Card from "./components/Card";

  export default {
    name: 'app',
    props: ["cid"],
    components: {
      Images,
      Video,
      TextType,
      Card
    },
    mounted() {
      axios({method: "GET", "url": this.contentDeliveryUrl}).then(result => {
          // eslint-disable-next-line
          this.content = amp.inlineContent(result.data)[0];
          console.log(this.content)
        }, error => {
          console.error(error);
        });
    },
    data() {
      return {
        contentDeliveryUrl: 'https://c1.adis.ws/cms/content/query?fullBodyObject=true&query=%7B%22sys.iri%22%3A%22http%3A%2F%2Fcontent.cms.amplience.com%2F${this.cid}%22%7D&scope=tree&store=testing',
        content: [],
        cidItem:'7e4301de-9c6e-4fab-9e68-3031b94d662d'
      }
    }
  }
</script>

If your components share similar structures, consider utilizing mixins. Create a file named myMixins.js with the code below:

const myMixins = {
 props:['cid'],
  mounted() {
    axios({
      method: "GET",
      "url": this.contentDeliveryUrl
    }).then(result => {
      // eslint-disable-next-line
      this.content = amp.inlineContent(result.data)[0];
      console.log(this.content)
    }, error => {
      console.error(error);
    });
  },
  data() {
    return {
      contentDeliveryUrl: 'https://c1.adis.ws/cms/content/query?fullBodyObject=true&query=%7B%22sys.iri%22%3A%22http%3A%2F%2Fcontent.cms.amplience.com%2F${this.cid}%22%7D&scope=tree&store=testing',
      content: []
    }
  }
}

export default mixins;

In each component, include the following:

    import myMixins from './myMixins'
    export default{
          ....
         mixins: [myMixin]
      }

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

Get the file using jQuery ajax post request

Currently, I am attempting to export the data from my web page and download it as an Excel file. However, despite receiving a successful response, the download does not initiate. $.ajax({ type: "POST", url: _url, contentType: 'multi ...

JavaScript - incorrect order for compiling

Is the user already in my SQLite database? If the user exists: return 500 (ERROR!!) If the user does not exist: return 200 (OK) This is my Node.js + Express script running on the server side. app.post('/adduser', function(req, res){ db.se ...

jQuery does not support displaying output using console.log

I have a JavaScript code that uses jQuery. However, when I click the #button_execute button, the console.log inside the callback function of .done doesn't display anything on the console. I'm not sure how to troubleshoot this issue. $("#button_e ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

Keep a close eye on your Vue app to make sure it's

<template> <v-form :model='agency'> <v-layout row wrap> <v-flex xs12 sm12 lg12 > <v-layout row wrap> <v-flex xs12 md12 class="add-col-padding-right"> <v-radio-group v-mod ...

How can I make sure a Post method finishes executing before returning the result of a Get method in Express.js?

I am currently utilizing the Ionic framework and Express to facilitate communication between my application, a server API, and a JavaScript game. The game transmits information to the API through XMLHttpRequest and post requests, while my application retri ...

Enable/Disable Text Editing Based on Vue Js Input

I’m working on a way to make certain parts of a string in an input editable or non-editable (readonly) depending on the context in Vue.js. For instance: I have this text: My Name is $John Doe$ Now, I want my Vue.js code to scan the string and allow edi ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Utilize the input type=date value in the date function to obtain a specific format

How can I pass the value of input type=date to a JavaScript date function? In my HTML code, I have used: <input type=date ng-model="dueDate"> <input type="time" ng-model="dueTime"> <button class="button button-block" ng-click="upload_dueda ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Storing form data in a JSON file using JavaScript

For a while now, I've been pondering over this issue. My plan involves creating a desktop application with Electron. As a result, I am working on an app using Node.js and Express.js. The project includes a simple app.js file that executes my website&a ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

Stopping React from re-rendering a component when only a specific part of the state changes

Is there a way to prevent unnecessary re-renders in React when only part of the state changes? The issue I'm facing is that whenever I hover over a marker, a popup opens or closes, causing all markers to re-render even though 'myState' rema ...

Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. Thi ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

Utilizing Grunt to streamline a personalized project

I have set up Grunt as my "JS Task Runner". Node.js is installed in the directory "C:/Program Files". NPM has been installed in C:/users/Peterson/appdata/roaming/npm. Inside the npm folder, I have Grunt, Bower, and Grunt-cli. I am working on a pro ...

Discovering Vue.js Event Handling: How to Identify If a Key Is Pressed While the Mouse Hovers over a Specific Element?

I am currently developing a Vue.js 3 multi-item selection feature. Each item is displayed as a <div> element with a checkbox inside. One functionality I am trying to add requires detecting when the Shift key is held down while the mouse hovers over ...

Validation is performed on the Bootstrap modal form, ensuring that the modal is only loaded after the

In order to provide a better understanding of my website's file structure, I would like to give an overview. The index.php file dynamically adds many pages to my website. Here is the code from index.php: <?php include ('pages/tillBody.php ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

What are the steps for implementing responsive design animation in my particular scenario?

Can someone please help me with a strange bug in Chrome? I am trying to create a responsive design for my app. The width of the 'item' element should change based on the browser's width. It works fine when the page first loads in Chrome, b ...