Home » vue » How can I use svg's in Nuxt with Vue.js without importing them?

How can I use svg's in Nuxt with Vue.js without importing them?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m working with Nuxt and Vue.js and I’m trying to render some svg’s to the page. But I keep getting the following

enter image description here

Don’t mind the pink, that’s from another element. I tried installing @nuxtjs/svg and I added it to my modules in my nuxt.config.js and it says it’s supposed to work right out of the box. But for me it isn’t. What am I doing wrong?

flagPath returns /vector/icons/flags/united_kingdom.svg and that’s where they are located. It works fine with png’s in the same folder.

<template>
  <div>
      <img :src="flagPath" width="70" height="38" />
  </div>
</template>

<script>
export default {
    props: ['default'],
    data(){
        return{
            folder: '/vector/icons/flags',
            fileName: {'uk' : '/united_kingdom.svg', 'south-korea' : '/south_korea.svg'},
        }
    },
    computed:{
        flagPath: function()
        {
            return this.folder + this.fileName[this.default];
        }
    }
}
</script>
Answers:

Try this when it’s in the static directory:

<img src="/vector/icons/flags/united_kingdom.svg" width="70" height="38" />

When you wanna reference static files inside HTML you can simply reference them with a forward slash.

###

If svg is in the assets folder, simply writing the path will not work
Because it goes through webpack
https://nuxtjs.org/docs/2.x/directory-structure/assets#images

:src="require('~/assets/...')"