Home > Software design >  How to load Axios Response before Vue Component renders?
How to load Axios Response before Vue Component renders?

Time:10-24

I want to use:

homePage.image = 'storage/'   'rkiGXBj7KJSOtsR5jiYTvNOajnzo7MlRAoXOXe3V.jpg'

inside:

<div class="home-image" :style="{'background-image': 'url('   homePage.image   ')'}"></div>

before the Vue Component is rendered but homePage.image returns "".

This is my component:

<template>
  <section id="home" class="home">
    <div class="image-container">
      <div class="home-image" :style="{'background-image': 'url('   homePage.image   ')'}"></div>
    </div>
  </section>
</template>


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

const homePage = ref({
    image: ""
});

axios.get('/home')
    .then(res => {
        homePage.image = 'storage/'   'rkiGXBj7KJSOtsR5jiYTvNOajnzo7MlRAoXOXe3V.jpg'; // storage link   image file name
    })
    .catch(err => {
        console.log(err.response);
    });

// works
// const image = 'storage/'   'rkiGXBj7KJSOtsR5jiYTvNOajnzo7MlRAoXOXe3V.jpg';

</script>

How do I get homePage.image to update to 'storage/' 'rkiGXBj7KJSOtsR5jiYTvNOajnzo7MlRAoXOXe3V.jpg' before it is loaded into the Component from inside the axios function?

CodePudding user response:

When you use ref for reactivity you must use value:

homePage.value.image = 'storage/'   'rkiGXBj7KJSOtsR5jiYTvNOajnzo7MlRAoXOXe3V.jpg';
  • Related