Inquiry regarding the life cycle of Vue 3 and the accessibility of its properties

I am trying to dynamically load content in a Vue component based on a specific argument provided. Here is an example code snippet:

ParentComponent.vue

<Suspense>
<div class="row g-0">
  <div class="col-md-3">
    <ChildComponent json-url="some/url/to/json/data" />
  </div>
  <div class="col-md-3">dt;
    <ChildComponent json-url="some/url/to/json/data" />
  </div>
  <div class="col-md-3">
    <ChildComponent json-url="some/url/to/json/data" />
  </div>
  <div class="col-md-3"t;
    <ChildComponent json-url="some/url/to/json/data" />
  </div>
</div>

<template #fallback>
  <p>Loading...</p>
</template>

ChildComponent.vue

<template>
 <!-- Display content based on the loaded JSON data -->
</template>

<script setup>
  import { ref, onMounted} from 'vue';
  

  defineProps({jsonUrl: {
    type: String,
    default: ""
  }})
  const images = ref(null);
  const thumbnail = ref(null);
  const title = ref("");
  const description = ref("");

  onMounted(async () => {
    try {
      const response = await fetch(new URL(jsonUrl, import.meta.url).href);
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      var jsonData = await response.json();

      images = jsonData["images"];
      thumbnail = jsonData["thumbnail"];
      title = jsonData["title"];
      description = jsonData["description"];
      console.log(thumbnail);
      
    } catch (error) {
      console.error('Error fetching the JSON file:', error);
    }
  });

</script>

The issue I'm encountering is that the jsonUrl doesn't seem to be accessible during the onMounted() callback. Despite correct naming and implementation, it's not recognized within this function. However, when using <p>{{json}}</p> directly in the template, the URLs are displayed correctly.

Although I've searched for solutions, it appears that the property should be accessible. For instance, a post on StackOverflow here demonstrates a similar approach (only difference being TypeScript usage). How can I properly load and initialize my content based on JSON data within my child component in this scenario?

Answer №1

Before starting, make sure to set up the props variable like this:

const props = defineProps({url: {
  type: String,
  default: ""
}})

Now you can use props.url to retrieve the prop. This will enable you to access the prop within the onMounted function.

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

Constructing items within an array literal using a constructor method

I am attempting to create an object using my Person constructor. However, I am encountering issues when I try to initialize the object directly in the array using literal notation. function Person(name, age) { this.name = name; this.age = age; } ...

"Click to view the latest data visualization using the Chart.js

I am exploring ways to enhance the animations in Chart.js for a new web project. The content is organized in tabs, with the chart displayed on the third tab out of four. Currently, the chart animates upon loading. How can I make it so that when #chartTrig ...

When the program is executed, immediately use .trigger('click')

There is a spelling game that features a grid filled with hidden words. The objective of the game is to spell out these words by clicking on the letters of the alphabet, aided by hints such as images and sounds. Players are given the word they need to spe ...

Accessing a key using Vuefire within a v-for loop

Recently embarking on the Vue and Vuefire journey, I am experimenting with creating dynamic links to different pages using unique keys as URL IDs. The database reference is configured as let db = app.database(); const postsRef = db.ref('posts') ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

Unlocking Google contact pictures using Google contacts API - A step-by-step guide

Exploring the Google contacts API with Node.js I've successfully retrieved all the contacts via the Google feed API, but without images https://www.google.com/m8/feeds/photos/media/faizy04%40gmail.com/ya29.ZAFTNcQ6sEue40gFqH5h8h91k8LO8Bwvf50NUgQKKms ...

What is the process Wikipedia uses to transform keywords into clickable links?

Currently, I am working on a Node.js project involving a model called "tags". I am looking for a way to automatically turn any tags mentioned in comments into links leading to the relevant tag page. For instance, if a user types out "What is a chicken?", I ...

Triggering a modal window with unique content by clicking on various images

Is there a way to trigger a modal window through clicking on an image? Additionally, can different images open different content upon clicking? I am planning to showcase a portfolio where clicking on an image will activate a modal that displays other image ...

You should only call them after the method that returns a promise has completed

submitTCtoDB() { console.log("The selected file list contains: " + this.selectedFileList) this.readFile().then(() => { alert("ReadFile has finished, now submitting TC"); this.submitTC() }); } readFile() { return new Promise((resolve, r ...

Uploading information by merging form data with a fetch API reply

In my project, I am looking to merge two sets of data into a specific format and then make a post request. After using the fetch API, I received the following response: { "id":"some-id" } The JSON format of my form data is as follows: { "origin_ ...

Use multiple lines to create a stunning visualization using morris.js. Let your data

I need help creating a graph using morris.js with 2 lines. I have two sets of data in one array, but I can't seem to display both lines on the graph simultaneously. When I use todos[0], only the first line is visible, and when I use todos[1], only the ...

Parsing dates in Firefox using Moment.js and AngularJS

I'm currently incorporating Moment.js into my project and parsing a normal date string like "21-jun-2020". However, I've noticed that the parse result differs between Chrome and Firefox. _d: Mon Jun 21 2021 00:00:00 GMT+0530 (India Standard Time ...

Leverage the power of multiline JavaScript expressions within your React components

I am facing a situation where I have the following React function component source code: return ( result.map(item => ( <tr key={item.id}> <td> {new Date(item.pub_date).getFullYear()} / {new Date(item.pub_date).getMont ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

Staying connected with Ajax

I've developed a create_event.php page where users can input event details. After completing the form, they have the option to log in. Upon successful login, I aim to display 'Hello $username, you are now logged-in' without reloading the pag ...

Testing components in Cypress does not support composables from VueUse due to the error message "ref is not defined."

I'm facing an issue where VueUse is causing my tests to break in Cypress component testing. No matter which composable I utilize, it throws errors like > ref is not defined or > watch is not defined. Upon examining the sources, I discovered that ...

Is React failing to communicate with Express?

As a newcomer to Node.js, react, and Express, I am working on building a basic application but encountering difficulties initializing express. Upon running npm start, the terminal displays the following message: ./node_modules/express/lib/view.js ...

Using radio buttons and a price slider, a unique jQuery filter for products can be

I have successfully implemented basic functionality to filter products based on price (slider) and radio boxes. However, the current filter system uses OR logic, but I need it to use AND instead. For instance, I want to find a product that is from Brand1, ...

Fetch file name using Ajax

I am struggling to retrieve the extension and name of a file using Ajax. This is my ajax code: $.ajax({ type: "POST", url: url, data: $("#updateMember").serialize(), mimeType: "multipart/form-data", contentType: false, cache: fal ...

Position the logo at the center of the Vuetify navigation bar

In my Vue/Vuetify application, the navigation bar consists of several elements: A hamburger menu An SVG logo that is linked to the homepage Various navigation links I am trying to style the elements as follows: left-align the menu, center the logo, and r ...