Dynamic src attributes return 404 for images

magyarn
0
magyarn
commented a year ago

Hello! I'm having a problem where dynamic src attributes return a 404, but the same path works fine when it's hardcoded. I have an array of "project" objects in my store, each of which has an "image" key with a value of the image path. I'm storing my images in ~/static/images. How can I keep everything in my store without having to use a computed property to generate the image path? I found a previous issue (https://github.com/nuxt/nuxt.js/issues/2103) but couldn't see how it solves the problem.

store/index.js contents:

import Vuex from 'vuex'

const createStore = () => {
  return new Vuex.Store({
    state: {
      projects: [
        {
          title: "Michigan Online",
          type: ["UX Design", "UX Research", "Frontend Development"],
          image: "~/static/images/Michigan-Online.png",
          id: 0,
        },
        {
          title: "Viewpoint",
          type: ["UX Design", "Frontend Development"],
          image: "~/static/images/Viewpoint.png",
          id: 1,
        },
      ]
    }
  })
}

export default createStore

Results in 404:

<template>
  <section class="container">
    <h1>Home</h1>
    <ul>
      <li v-for="project in projects" :key="project.id">
        <article>
          <h2>{{ project.title }}</h2>
          <img :src="project.image" :alt="project.title">
        </article>
      </li>
    </ul>
  </section>
</template>

<script>

export default {
  computed: {
    projects () {
      return this.$store.state.projects
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~/assets/sass/main.scss";
</style>

Successful but hardcoded image path:

<template>
  <section class="container">
    <h1>Home</h1>
    <ul>
      <li v-for="project in projects" :key="project.id">
        <article>
          <h2>{{ project.title }}</h2>
          <img src="~/static/images/Michigan-Online.png" :alt="project.title">
        </article>
      </li>
    </ul>
  </section>
</template>

<script>

export default {
  computed: {
    projects () {
      return this.$store.state.projects
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~/assets/sass/main.scss";
</style>
0
Krutie
10
Krutie
commented a year ago

How about setting baseUrl in nuxt.config.js like this,

// nuxt.config.js

module.exports = {
  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  }
  ...
}

And then in your projects.image key in store.state, define image path like this,

// store/index.js

projects: [
 {
   title: 'Michigan Online',
   type: ['UX Design', 'UX Research', 'Frontend Development'],
   image: process.env.baseUrl + '/images/Michigan-Online.png',
   id: 0,
 },
 ...
]

Also, you can get away without writing /static/ in the image path this way.

0
Informations
Question โ€ข Unresolved
#c7085 - Created a year ago