Image Templating with Vue.js

The Image field allows content writers to upload an image.

Before Reading

This page assumes that you have already included the prismic-vue plugin in your project or that you are using the Prismic Vue.js starter. Check out the Integrating with existing project page to learn how to get setup.

Usage

Here's an example of how to integrate an Image field into your template.
In this example, the Image field has the API ID of illustration.

Copy
<template>
  <div>
    <prismic-image :field="fields.illustration"/>
  </div>
</template>

<script>
export default {
  data () {
    return {
      fields: {
        illustration: null
      }
    };
  },
  methods: {
    // This is an example query, the important part is above.
    getContent () {
      this.$prismic.client.getSingle('example')
        .then((document) => {
          this.fields.illustration = document.data.illustration;
        })
    }
  },
  created () {
    this.getContent();
  }
};
</script>

Note that the alt attribute is strongly recommended in HTML5 for the image element. We advise to always write an alternative text for each image uploaded to your Prismic's media library. Check out the user guide on how to add metadata to an asset.

Image properties

The example above will generate an <img> element with its src and alt attributes filled (plus copyright if there is one). You can also retrieve this data manually, including the width and height of the image. For example, let's imagine you have already retrieved your document which contains an Image field with an API ID of background.

Copy
const background = document.data.background;
const url = background.url;
const alt = background.alt;
const copyright = background.copyright;
const width = background.dimensions.width;
const height = background.dimensions.height;

Responsive views

Here's an example of how to integrate an Image field with responsive views into your template.
In this example, the Image field has the API ID of landscape.

Copy
<template>
  <div>
    <picture>
      <source :srcset="mobileView.url" media="(max-width: 420px)">
      <source :srcset="tabletView.url" media="(max-width: 840px)">
      <img :src="mainView.url" :alt="mainView.alt">
    </picture>
  </div>
</template>

<script>
export default {
  data () {
    return {
      mainView: {},
      tabletView: {},
      mobileView: {}
    };
  },
  methods: {
    getContent () {
      this.$prismic.client.getSingle('example')
        .then((document) => {
          this.mainView = document.data.landscape;
          this.tabletView = document.data.landscape.tablet;
          this.mobileView = document.data.landscape.mobile;
        })
    }
  },
  created () {
    this.getContent();
  }
};
</script>

To learn more about the Image field check out the user guide.