Published on

How to use images in Vue.js: A complete guide

Authors

How to use images in Vue.js: A complete guide

Vue is a very popular JavaScript front-end framework (they help us create modern applications and are mostly used on the web) that’s experiencing a huge amount of growth. It’s simple, tiny (~24KB), and very performant. It feels different from all the other JavaScript front-end frameworks and view libraries.

Frameworks abstract the interaction with the browser and the DOM. Instead of manipulating elements by referencing them in there, we declaratively define and interact with them at a higher level. Using a framework is like using the C programming language instead of using the assembly language to write system programs, they basically make your life easier.

And on that note, vue is called a progressive framework! Meaning it adapts to the needs of the developer, in this case, you!

But first things first, what is Vue.js exactly?

Vue is a progressive framework for building user interfaces. It’s designed from the ground up to be used incrementally. The central library is focused only on the visualization layer, and it is easy to use and integrate with other existing libraries or projects.

Vue lands inside your app with a simple script tag to start with and it can grow along with your needs, spreading from 3 lines to managing your entire view layer. It’s capable of driving sophisticated single-page applications when used in combination with modern tools and supporting libraries too!

The easiest way to try out Vue.js is by creating a file index.html and include Vue with <script src = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> or, with <script src="https://cdn.jsdelivr.net/npm/vue"></script>

It’s important to note that Vue is not backed by a huge corporation like Facebook or Google. Instead, it’s completely backed by the community, which fosters development through donations and sponsors and thus making sure the work plan of Vue is not driven by a single company’s agenda, which can give the consumer more confidence and a sense of calmness.

Vue components:

Now that you have a pretty clear idea of what Vue.js is, you should learn what a vue component is.

Components **are single, independent units of an interface who can be a way to write modular, reusable code for your Vue.js application. They can be thought of as custom HTML elements** that can be used by your main Vue instance and/or by other components (they can also be thought of as mini- or sub- Vue instances)

Inside the world of vue.js they can be defined in many ways, but below we’re going to show you the four main ways:

  • First one: new Vue({ /* options */}). This one is used when you're building an application that is not a Single Page Application (SPA), and since it has no corresponding tag name, it's usually the main container component.
  • Second one: Vue.component('component-name', { /* options */}). This one allows you to define a tag with which you can embed the component multiple times in the application and specify the output of the component in the template property.
  • Third one: this one uses local components (only accessible by a specific component). You can encapsulate components locally by assigning an object that defines the component object to a variable and then make it available inside another component by using the components property.
  • Fourth one: single file components, or .vue files (a .vue file is a custom file format that uses HTML-like syntax to describe a Vue component).

To create a component, you can register it globally with the component method of the Vue constructor:

Vue.component('some-component', {

/* data, methods, etc. go here */

});

Here’s an example of a Vue component:

Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

Single File Components

A Vue component can be declared in a JavaScript file (.js) like this:

Vue.component('component-name', {  /* options */})

like this:

new Vue({  /* options */})

Or, it can be specified in a .vue file, which allows you to define JavaScript logic, HTML code template and CSS styling all in just a single file. That’s why it has the name of Single File Component!

Component library:

A component library is a set of reusable components and it can be small or large, it can be a distributed package on npm,i t could be a folder inside your project with common components used throughout the application, etc.

As we saw, .vue is a popular JavaScript library you can use to create dynamic applications on the frontend, and one of the reasons for Vue’s popularity is the ease it provides developers creating web components. As a result, a lot of people have been creating vue component libraries that are fast-growing and help to simplify various aspects of development with them!

Here are the top 10 vue component libraries: Element UI, Vuetify, Bootstrap Vue, Buefy, Vue Material, Quasar, Vux, iView, Vue Material Kit and Mint UI.

Another way of creating a vue component library is by using the vue-sfc-rollup npm package.

  1. To do this, you first install the vue-sfc-rollup globally: npm install -g vue-sfc-rollup.
  2. Once that is installed (from the command line), go into the directory where you want your library project to be located. Once you are in that folder, run the following command to initialize the project: sfc-init
  3. After the setup is complete, navigate to your folder and run an npm install:

cd path/to/my-component-or-lib

npm install

  1. Once that is done, you can open the folder up in your editor of choice! There is a sample Vue component built for you and you can find it inside of the /src/lib-components folder. You can also add your own custom component by creating a new Vue file inside of the lib-components folder.

You can copy and paste this code into your file:

<template>

  <button class="btn-cta">{{ text }}</button>

</template>

<script>

export default {
  name: "FccButton", // vue component name
  props: {
    text: {
      type: String,
      default: "Enter Button Text Here"
    }
  },
  data() {}
};

</script>

<style>

.btn-cta {
  background-color: #d0d0d5;
  border-width: 3px;
  border-color: #1b1b32;
  border-radius: 0;
  border-style: solid;
  color: #1b1b32;
  display: block;
  margin-bottom: 0;
  font-weight: normal;
  text-align: center;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  white-space: nowrap;
  padding: 6px 12px;
  font-size: 18px;
  line-height: 1.42857143;
}

.btn-cta:active:hover, .btn-cta:focus, .btn-cta:hover {
  background-color: #1b1b32;
  border-width: 3px;
  border-color: #000;
  background-image: none;
  color: #f5f6f7;
}

</style>
  1. To see how the component looks, you will need to add it to the index.js file located in the lib-components folder. Your index.js file should look like this:
/* eslint-disable import/prefer-default-export */

export { default as FccButton } from './FccButton';
  1. And you'll also need to import the component into the serve.vue file inside of the dev folder to look like this:
<script>
import Vue from "vue";
import { FccButton } from "@/entry";
export default Vue.extend({
  name: "ServeDev",
  components: {
    FccButton
  }
});
</script>

<template>
  <div id="app">
    <FccButton />
  </div>
</template>

Just make sure you are exporting them in the /lib-components/index.js file and that is it! You've now published a Vue component library!

Now, here are some of the most common questions regarding .vue files and images:

How do I use images inside my .vue single file components?

Are you wondering how you can insert images inside the <template>?

Use ‘require’!

<template>
  <img v-bind:src="require('images/rails.png')" />
</template>

How can I add images in data object vue.js?

Here is an example code on how to do that:

<template>
  <div id="app">
    <img :src="image" />
  </div>
</template>

<script>

import image from "./assets/logo.png"

export default {
  data: function () {
    return {
      image: image
    }
  }
}

</script>

How do you upload images to vue.js?

First, select a file (make sure to add <input type="file"> to your component template code).

Then you need the “two handler methods” in your .vue component:

methods: {
  onFileChanged (event) {
  const file = event.target.files[0]
},

onUpload() {
// upload file
}

Then, you send the file to a server (you can use axios).

With the file stored in state, you can send it as binary data or wrapped in a form data object.

As binary data:

onUpload() {
  axios.post('my-domain.com/file-upload', this.selectedFile)
}

As form data:

onUpload() {
  const formData = new FormData()
  formData.append('myFile', this.selectedFile, this.selectedFile.name)
  axios.post('my-domain.com/file-upload', formData)
}

And that is it! Image uploaded!

How to add a Background Image in Vue?

You can add a background image by using inline styles in different ways, but, here is an example on doing so by storing the style object inside vue data property:

<template>
  <div :style="image"></div>
</template>

<script>
export default {
  data() {
    return {
      image: { backgroundImage: "url(https://vuejs.org/images/logo.png)" }
    };
  }
};
</script>

And here is an example if your background image comes from your backend server:

<template>
  <div :style="{backgroundImage:`url(${post.image})`}"></div>
</template>

If you’re interested, you can learn more about background images by reading this article on how to use responsive images with CSS Background srcset!

How to pass variables to inline background images in .vue?

Passing a style binding into Vue is easy! You can do it like this:

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

Or, you can use directly from the variable like this:

<template>
  <div class="progress">
    <div class="progress__fill" :style="{ width: progress }"></div>
  </div>
</template>

<script>
  export default {
    props: ["percent"],
    data() {
      return {
        progress: this.percent + "%",
      };
    },
  };
</script>

But how would you pass the data if the background image is dependent on the data binding?

If you have static data, you can import the file and pass it into Vue data binding.

<template>
  <div 
    class=" bg-no-repeat bg-cover  bg-white hero relative" 
    :style="{ backgroundImage: `url(${backgroundUrl})` }"
  ></div>
</template>

<script>

import backgroundUrl from "~/assets/img/bg-wp.png";

export default {
  data() {
    return {
      backgroundUrl,
    };
  },
};

</script>

If you have dynamic data, you can directly pass the variable into the inline-style

<template>
  <div
    class="min-h-screen bg-grey bg-cover flex items-end block md:fixed w-full md:w-1/2 shadow-md"
    :style="{ backgroundImage: `url(${member.coverImage})` }" >

    <p>{{ member.name }}</p>
  </div>
</template>

<script>

export default {
  data() {
    return {
      member: {
          name: "Jakz",
          coverImage: "<https://vuejs.org/images/logo.png>",
      },
    };
  },
};

</script>

In conclusion,

We hope this guide helped you understand more of the immense world of vue.js and made you realize that it is not as hard as it seems, especially if you already have background knowledge on Javascript and HTML like yourself!

If you feel like learning more, check out these articles ;)

What is a React Image? – Piio Blog