Jaeger
Jaeger

Reputation: 1754

How do I correctly use my inherited datas from my parent component?

I'm a newbie with VueJS and I'm setting up a rather simple website where the user can change some elements from the website, such as the website's background image.

From the admin part of the website, the user can upload an image that will be used as one of the page's background. The value is stored in a Rails API, and, when a user gets to the visitor's part, VueJS calls the settings from Rails, then displays it where I want them. I use Vue-Router, so I make the call for the settings in my App.vue and transmit the received datas to the <router-view> component. I decided to do so to load all the datas only once instead of loading them for each page change.

Here is how it looks:

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>
  <!-- Some other elements, not related -->
  </div>
</template>

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

<style scoped>
</style>

I have several problems with this configuration:

I guess this is a problem with asynchronous loads, but how should I handle that? Should I use VueX?

Thank you in advance

Upvotes: 0

Views: 47

Answers (2)

Erubiel
Erubiel

Reputation: 2972

I tried to declare with datas() what structure this.settings will have, but VueJS tells me that it doesn't like how there are two settings declared.

No, declare it on the props, like this

props: {
    'settings': {
        type: Object,
        default: () => ({
            landing_bg: {
               url: '' //here you can specify a default URL or leave it blank to just remove the error
            }
        })
    },
},

Upvotes: 0

dziraf
dziraf

Reputation: 3653

First of all, this is redundant in your :style, change it to:

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

By the way, unless your landing_bg.url looks like this: url('bg_url') you might want to create a computed property:

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

You might also have to add a v-if in that div to render it only after settings have been loaded. That error pops up because settings is still null when the component is created.

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

Upvotes: 2

Related Questions