What is the proper way to utilize the data inherited from my parent component?

As a newcomer to VueJS, I am in the process of setting up a simple website that allows users to customize certain elements, such as the background image.

Users can upload an image from the admin section of the website, which will then be used as the background on a particular page. The data is stored in a Rails API, and when a user visits the site, VueJS retrieves the settings from Rails and displays them accordingly. Using Vue-Router, I make the call for the settings in my App.vue and pass the data to the <router-view> component. This way, all the data is loaded only once instead of reloading it for each page change.

This is how it is set up:

App.vue

<template>
  <div id="app">
    <transition :name="transitionName">
      <router-view :settings="settings" :me="bio"></router-view>
    </transition>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      settings: null
    }
  },
  created () {
    this.$http.secured.get('/settings')
      .then(response => {
        this.settings = response.data
      })
      .catch(error => this.setError(error))
  }
}
</script>

front/Landing.vue

<template>
  <div id="landing" :style="{background: this.settings.landing_bg.url}">
  <p>{{ this.settings.landing_bg.url }}</p>
  <!-- Other unrelated elements here -->
  </div>
</template>

<script>
export default {
  props: ['settings'],
  created () {
    console.log(this.settings)
  }
}
</script>

<style scoped>
</style>

I am facing several challenges with this setup:

  • The first issue is that VueJS throws errors stating it cannot read "landing_bg" of null

  • However, VueJS has no trouble displaying the image's path in the <p> element right below it

  • console.log(this.settings) returns null upon page reload, but displays the settings correctly if I navigate to another page and return. Nevertheless, the background image does not load.

  • I attempted to define the structure of this.settings using datas(), but VueJS raised an error indicating it did not approve of having two declarations of settings.

It seems like an asynchronous loading issue, but what would be the best way to handle it? Should I consider using VueX?

Thank you for your help and insights

Answer ā„–1

To start off, it is important to note that the use of this in your :style is unnecessary. You should modify it to:

:style="{ background: settings.landing_bg.url }"

Additionally, if your landing_bg.url does not follow the format url('bg_url'), you may want to consider creating a computed property:

computed: {
  bgURL() { return `background: url('${this.settings.landing_bg.url}')` }
}

You might also need to include a v-if statement within the div to ensure it only renders after the settings have been fully loaded. The error occurs because settings is still null during component creation.

<div id="landing" :style="bgURL" v-if="settings">

Answer ā„–2

When attempting to specify the structure of this.settings using datas(), VueJS alerted me that having two settings declared is not acceptable.

Instead, declare it in the props section like so:

props: {
    'settings': {
        type: Object,
        default: () => ({
            landing_bg: {
               url: '' //you can set a default URL or leave it empty to remove any errors
            }
        })
    },
},

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

Leveraging the firebreath plugin to trigger a folder dialog, enabling asynchronous selection of folders to preserve the smooth execution of Java Script without any blocking

I need to ensure that only one folder selection dialog is open at any given time. Once the user picks a folder, an event will be triggered to notify the JavaScript of the selected folder. In order to open the dialog, I have integrated code from this gist ...

Looking for a way to store data in local storage so it remains even after the page is reloaded? I tried adding a local storage function, but it doesn't appear to be

I am currently working on a project involving a work day scheduler and I am facing challenges in saving data within the schedule events, like at 8am, and making sure it persists on reload. The colored time block element that changes as hours pass in the da ...

Trouble with adding an object to an array in AngularJS

I'm having trouble pushing an object to an array. I'm trying to push the comments object (values from forms) on submit click, into dish.comments in dishDetailController. The ng-controller="DishCommentController" is nested inside ng-controller="di ...

JavaScript program to split an array of strings into sets of arrays based on alphabetical order

I am looking to split an array of strings into multiple arrays based on alphabetical order. Can you help me achieve this? For example: let array = ['cheese', 'corn', 'apple', 'acorn', 'beet', 'banana ...

Tips for defining boundaries for position absolute elements using JavaScript

Fiddle. I am in the process of developing a chat/mail application with a resizable menu similar to the Google Hangouts desktop app. When resizing the brown content pane at a normal speed, you can observe that the boundaries are functioning as intended. My ...

How to generate a dropdown menu using a deeply nested JSON array

I'm looking to create a series of drop-down lists based on the JSON array provided below. There will be five drop-down lists, and when I select an option in one list, the other four should populate accordingly. For example, if I choose "Hindi" in the ...

Scrolling through the page, press the "Read Less"

I've implemented a Read More/Read Less button feature for product descriptions on my website. One issue I'm facing is that when I click the Read Less button at the bottom of the extended description, the text shortens as expected but the page do ...

Preventing Duplicate Content in jQuery.ajax when Posting Data on the Same Page

Issue 1: I am experiencing content overlap after sending data back to the same page using jQuery.ajax(). This is necessary as I need to transfer JavaScript values to PHP. How can I modify my code to prevent the content from duplicating before and after pos ...

Guide to creating an object using a loop in typescript without relying on `Partial` to assign keys from a list

Introduction I am currently facing a challenge with initializing an object with predefined keys. The issue arises when I try to start with an empty object {} as it interferes with my typing. The Issue: I have a set of values that I want to use as keys an ...

Troubleshooting: Implementing JavaScript to dynamically append elements to a list on a webpage

Can someone help me troubleshoot why my Chrome extension isn't working properly? I'm trying to create a simple To-do list extension for myself using the code below: HTML: <html> <head> <link rel="stylesheet" typ ...

What is the best way to adjust the font size in CSS/JS so that it creates a specific margin on the sides of its container?

Is it possible to create a font size that is perfectly scaled to fit within a specific container? For example, I would like the text to have 8% margin on each side of the container, and fill the remaining 84%. How can this be achieved using HTML/JS/CSS? ...

"Exploring the Latest ThreeJS Enhancements Beyond the Standard

Is it acceptable to update values outside of the animate() loop? Could updating values outside the loop impact render performance? The potential drawback is that some updates might not be fully completed until the next animate call. Are there any other ...

What is the quickest way to find and add together the two smallest numbers from a given array of numbers using JavaScript?

const getSumOfTwoSmallestNumbers = (numbers) => { const sortedNumbers = numbers.sort((a, b) => a - b); return sortedNumbers[0] + sortedNumbers[1]; } I encountered this challenge on Code Wars. My function to find the sum of the two smallest num ...

Creating files using the constructor in Internet Explorer and Safari

Unfortunately, the File() constructor is not supported in IE and Safari. You can check on CanIUse for more information. I'm wondering if there's a workaround for this limitation in Angular/JavaScript? var file = new File(byteArrays, tempfilenam ...

Unable to progress in an HTML5 Drag and Drop application

I am currently learning HTML5 and I have encountered an issue with a specific example. The code is running without errors, but the drag and drop functionality is not working as expected. I have included the code snippet below. Could you please review it fo ...

Changing the ID of a textbox can be done by modifying the corresponding

I need to dynamically generate textboxes, checkboxes, and buttons based on user input during runtime. Users should be able to delete a specific textbox, checkbox, and button by clicking a button. The creation process is working correctly. However, when ...

Is it achievable to have a background image cover size with a responsive rollover effect?

Iā€™m currently facing a unique challenge where I want to have an image as the background of my website, with the size set to cover the entire screen. On this background image, there are elements like buildings that I want to interact with when hovered ove ...

Encountering error message "Module not found '@angular/compiler-cli/ngcc'" while attempting to run "ng serve" for my application

Encountering an error while trying to run my app, I have attempted various solutions available online. These include uninstalling and reinstalling angular/cli, verifying the correct version in package.json (ensuring it is "@angular/cli" and not "@angular-c ...

Guide to successfully merging Mysql data with PHP into the ParamQuery Grid using Javascript

Could you please assist in converting the JSON output from MySQL into the desired format shown below? JSON [ {"storenm": "S1", "FA_SOH": "20964", "FA_CY_QTY": "15", "FA_CT_QTY": "44497"}, {"storenm": "S2", "FA_SOH": "1096", "FA_CY_QTY": "2", "FA_ ...

Having a single post functioning correctly, however encountering a 500 error when attempting to loop through

Whenever I upload an image individually, it saves successfully and returns a 200 response. However, when I attempt to convert it into a loop, I receive a 500 error. Despite both methods saving the image to s3, I am puzzled as to where the 500 error is orig ...