How can I import a svg file to a Vue component?
In vue single file component.I import a svg file like this:
import A from 'a.svg'
And then how can I use A in my component?
Solution 1:
Based on the information you provided, what you can do is:
- Install vue-svg-loader
npm install --save-dev vue-svg-loader
- Configure webpack:
module: {
rules: [
{
test: /\.svg$/,
loader: 'vue-svg-loader', // `vue-svg` for webpack 1.x
},
],
},
- Import the svg and use it as a regular component:
<template>
<nav id="menu">
<a href="...">
<SomeIcon class="icon" />
Some page
</a>
</nav>
</template>
<script>
import SomeIcon from './assets/some-icon.svg';
export default {
name: 'menu',
components: {
SomeIcon,
},
};
</script>
Reference: https://github.com/visualfanatic/vue-svg-loader
Solution 2:
I've gotten the following to work in Vue 3. Doesn't require messing with webpack or installing any third party plugins.
<template>
<img :src="mySVG" />
</template>
<script>
export default {
name: 'App',
data(){
return {
mySVG: require('./assets/my-svg-file.svg')
}
}
}
</script>
Note: I'm aware that you cannot modify certain pieces of the SVG when using it in img src, but if you simply want to use SVG files like you would any other image, this seems to be a quick and easy solution.