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

`Sending binary data to client through GraphQL: A comprehensive guide`

I have a GraphQL server running on express. I am looking for a way to send images back to the client using nodejs buffer objects instead of JSON. How can I configure my graphql server to return bytes directly, without encoding them in base64 due to large ...

Looking for assistance with my MEAN stack To Do App project development

For a test at an enterprise, I have been tasked with creating a "to do APP" using Node js, Express, MongoDB & Angular Js. This is new territory for me as I have never worked with the MEAN Stack before but I am excited to explore it! The base project has al ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

` `issues with fmt:massage tag` `

When I try to update my page elements using ajax, I encountered a problem: the fmt:message tag doesn't work when I set it in javascript. In the JSP page everything works fine: <div id="div"> <fmt:message key="search_select_country"/> & ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

Having difficulty locating the login button on the webpage

I am attempting to log into a banking account using selenuim. After opening the webpage and locating the login element, I initially struggled to access it by its "name" or "id." Fortunately, I was able to successfully access it using driver.find_element_by ...

Displaying the boolean value of a list item in an input field using Vue.js

I have a collection of data from a backend that includes strings, numbers, and booleans. These values need to be shown in text fields. I am using <b-input ... /> component from bootstrap-vue for the input field. It works fine with boolean, but th ...

Guide to setting up routes in nuxt.js

I am building a blog website with Nuxt.Js on the domain xyz.com. I would like to display different pages based on country code, such as xyz.com/en/home and xyz.com/en/about. Can someone guide me on how to define routes in Nuxt.js for displaying blog conte ...

What is the best approach to developing Vue components with unique templates while maintaining the same functionality without duplicating code?

I am working on a project to develop a custom and versatile datatable component. My goal is to be able to adjust the appearance of the datatable on each page, while maintaining consistent functionality. I want to pass data rows into the component and have ...

issue retrieving data from live website created with next.js

Hello, I've exhausted all possible avenues to identify the cause of the error occurring on my live website built with NEXTJS. I have observed that this error only occurs when I reload the website. It's worth noting that I can successfully login ...

What are the steps to resolve the vulnerability within vue-cli-service?

Recently, I set up a new project using @vue/cli 4.3.1 on a fresh installation of Ubuntu 19.10 with npm 6.14.4. Upon running npm install in the project directory, I received the following message: found 1 high severity vulnerability run `npm audit fix` t ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

Calculate the difference in days between two selected dates from an Ajax Datetime Picker using JavaScript

How can I use JavaScript to count the number of days between two selected dates from Ajax date time pickers in my aspx page? The script should automatically input this calculated value into a designated "Number_Of_Days" text box without requiring a page ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

What are the advantages and disadvantages of transmitting data to Vue through Blade Views in Laravel compared to sending it directly to Vue Components using Axios?

Currently, I am transferring data from Laravel to Vue (using MySQL DB's) in the following manner: routes/web.php: Route::get('/', [MyController::class, 'index']); app/Http/Controllers/MyController.php: public function index() { ...

What are the steps to utilize the .find() method to search for documents in a database that belong to the current user

My back-end code for the 'get' request to my '/logs' collection returns data in an array labeled "times": router.get('/', (req, res) => { time .find({'userName': req.params.userName}) .exec() .then(times => ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

Tips for sending information from a controller to jQuery (Ajax) in CodeIgniter

Code snippet in controller: $rates['poor'] = 10; $rates['fair'] = 20; $this->load->view('search_result2', $rates); //Although I have attempted different ways, the only successful method is using the code above. Other ...

Updating the route path for version control in Express.js

When working with an ExpressJS application, the following paths should be considered: GET /v1/users/detail GET /v2/users/detail The corresponding routers are as follows: // v1/users.js router.get('/v1/users/detail', (req, res, next) => res. ...

The functionality to disable and reenable a button after performing a calculation is not functioning properly in the code

Here's the issue I'm facing with my code: When I click the search button, a for loop prints "hi" 5000 times. Before this loop starts, I want to disable the button. However, after the console.log is done, the button should be enabled again. But fo ...