How to generate <img> with SVG in a v-for loop in Nuxt.js?

Viewed 1118

Template:

  <div v-for="feature in features" :key="feature.label">
    <img :src="feature.icon">
    <div>
      {{ feature.label }}
    </div>
  </div>

Data:

features: {
  first: {
    icon: '~assets/svg/cards/first.svg',
    label: 'First label'
  },
  second: {
    icon: '~assets/svg/cards/second.svg',
    label: 'Second label'
  },
  third: {
    icon: '~assets/svg/cards/third.svg',
    label: 'Third label'
  },
  fourth: {
    icon: '~assets/svg/cards/fourth.svg',
    label: 'Fourth label'
  }
}

However I can't seem to find a way for this to work.

  • :src="feature.icon" returns http://localhost:3000/~assets/svg/cards/first.svg

  • installing nuxt-svg-loader adds [Vue warn]: Invalid prop: type check failed for prop "src". Expected String with value "[object Module]", got Module if you try to do the one above, in addition to the existing error

  • :src="require(feature.icon)" returns 'Cannot find module '~assets/svg/cards/first.svg''

  • x.icon: require('~assets/svg/cards/first.svg') returns 'Cannot find module '~assets/svg/cards/first.svg''

All the tutorials that I find online suggest the first method from the list above, but they all use .png/.jpg files

However, just <img src="~assets/svg/cards/first.svg"> without any additional modules works perfectly

2 Answers

I'd recommend that move your .svg files to static directory in root of your project so you don't have to worry about Webpack or any other config. your file will be available via /name.prefix

Change your data like below:

features: {
  first: {
    icon: '/svg/cards/first.svg',
    label: 'First label'
  },
  second: {
    icon: '/svg/cards/second.svg',
    label: 'Second label'
  },
  third: {
    icon: '/svg/cards/third.svg',
    label: 'Third label'
  },
  fourth: {
    icon: '/svg/cards/fourth.svg',
    label: 'Fourth label'
  }
}

And finally:

<img :src="feature.icon">

Reference: https://nuxtjs.org/guide/assets/

Related