Vue.js SVG Responsive Component

drozerah

Drozerah

Posted on July 2, 2019

Vue.js SVG Responsive Component

Simply Demonstrate a Vue.js component that returns a .svg file passed to the component as a property + turn the img html tag into a responsive/adaptative element using CSS rules

Method:

  • we use a computed property to work with the SVG file into the component.

note: Computed properties sit halfway between properties of the data object and methods: we can access them as if they were properties of the data object, but they are specified as functions...

  • we create a computed property function that returns the .svg file path using the require() method to access the assets folder
  • we create the full path to the .svg source file using the value stored/passed as the property (props) of the component this.SVGFile
  • we use the ES6 template literal syntax to construct the full path dynamically...
  • we bind the value of the computed property to the src attribute of the img html tag...
  • the responsive-img CSS class will let the img tag to automatically fit the size of its parent container

component src\components\SVG-image.vue

<template>
    <img class="responsive-img" alt="JS logo" :src="path">
</template>

<script>
export default {
  name: 'SVG-image',
  props: {
    SVGFile: String
  },
  computed: {
    path(){
      return require( `@/assets/svg/${this.SVGFile}`)
    }
  }
}
</script>

<style lang="scss" scoped>

.responsive-img{
  max-width: 100%;
  height: auto;
}

</style>
Enter fullscreen mode Exit fullscreen mode

Using the component src\App.vue

<template>
  <div id="app">
    <main>
      <SVGImage SVGFile='logo-js.svg'/>
    </main>
  </div>
</template>

<script>
import SVGImage from './components/SVG-image.vue'

export default {
  name: 'app',
  components: {
    SVGImage,
  }
}
</script>
//...
Enter fullscreen mode Exit fullscreen mode

gif

Check it out !

Get a local copy of this repository

$ git clone https://github.com/Drozerah/vue-svg-responsive-component.git
Enter fullscreen mode Exit fullscreen mode

Project setup

$ npm install
Enter fullscreen mode Exit fullscreen mode

Compiles and hot-reloads for development

$ npm run serve
Enter fullscreen mode Exit fullscreen mode

Compiles and minifies for production

$ npm run build
Enter fullscreen mode Exit fullscreen mode

Once you are done with the compilation, simply:

$ cd dist
Enter fullscreen mode Exit fullscreen mode

Then go live your index.html with your local development server...

That's it!

Vue.js SVG Responsive Component

Thanks for reading!

See you next time!

Drozerah

💖 💪 🙅 🚩
drozerah
Drozerah

Posted on July 2, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related