Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
shangxinbo Avatar asked Jun 22 '17 09:06

shangxinbo


People also ask

How do I import SVG into Vue?

Loading a standard HTML SVG At the end of the day, Vue uses dynamic HTML templating, meaning the most straightforward way to use SVG with Vue is exactly how you might do it with standard HTML: By placing the <svg> inline. By using an <img> tag that links to an external SVG file with the src attribute.

How do I import an image into Vue component?

To import and use image in a Vue. js single file component, we can set the src prop of the image to the image path returned by the require function. to set the src prop of the image to the path returned by require . We call require with the relative path of the image to return the resolved path of the image.

How do I import files to Vue?

There are two ways to import a JavaScript library to the Vue Component. The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey.


2 Answers

Based on the information you provided, what you can do is:

  1. Install vue-svg-loader

npm install --save-dev vue-svg-loader

  1. Configure webpack:

module: {      rules: [        {         test: /\.svg$/,         loader: 'vue-svg-loader', // `vue-svg` for webpack 1.x        },      ],    },
  1. 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

like image 90
Renato Krcelic Avatar answered Sep 20 '22 06:09

Renato Krcelic


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.

like image 24
Eric Uldall Avatar answered Sep 17 '22 06:09

Eric Uldall