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 itconsole.log(this.settings)
returnsnull
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
usingdatas()
, but VueJS raised an error indicating it did not approve of having two declarations ofsettings
.
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