Home  >  Q&A  >  body text

Vue3's style directive produces a 404 error when using background-image

I'm getting the reactive image link from the database via axios.get like this:

<div class="main-image" :style="{'background-image': 'url(' + state.articles.image[0] + ')'}">

Everything works fine, the background image of the div is changed correctly. The only problem is that my console throws:

GET http://localhost:3000/undefined 404 (Not Found)

Obviously this shows that url is not pointing anywhere, but how is this possible when background-image is displayed correctly? In my CSS I don't have the background-image property set, only background: no-repeat center but even if I remove these errors still exist . Any ideas how to get rid of 404?

Running console.log(state.articles.image[0]) before sending template to template will generate the correct image link:

storage/brrAlEXfmEvoqjXiRhgalgzT9f2MfbX07Q4wDL0i.jpg

Even if I output the link in the template (e.g. in an h tag) it shows the correct link, so what's the problem?

P粉186897465P粉186897465203 days ago382

reply all(1)I'll reply

  • P粉156983446

    P粉1569834462024-03-30 00:42:17

    The template will be rendered before state.articles.image[0] is known. The div tag is rendered and the browser will try to get the undefined background image url that has not been defined yet. One way to solve this problem is to only render <div> when the state is ready.

    reply
    0
  • Cancelreply