Home > Blockchain >  How to get images from blockcontent body?
How to get images from blockcontent body?

Time:07-05

This is my code. Everything renders except images. How to get images in the right order from body? I'm using sanity-blocks-vue-component to render body block. While fetching query Im also fetching body from it. Propably I should use serializers, but I don't know how I should implement that.

sanity-blocks-vue-component: https://github.com/rdunk/sanity-blocks-vue-component

export default {
  name: 'SinglePost',
  components: { SanityBlocks },
  data() {
    return {
      loading: true,
      post: [],
      blocks: [],
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    imageUrlFor(source) {
      return imageBuilder.image(source);
    },
    fetchData() {
      this.error = this.post = null;
      this.loading = true;

      sanity.fetch(query, { slug: this.$route.params.slug }).then(
        (post) => {
          this.loading = false;
          this.post = post;
          this.blocks = post.body;
        },
        (error) => {
          this.error = error;
        }
      );
    },
  },
};

Template:

<SanityBlocks :blocks="blocks" />

post.js in sanity folder

    {
  name: 'body',
  title: 'Body',
  type: 'blockContent',
},

CodePudding user response:

You need to serialize the image. Change the template to

<SanityBlocks :blocks="blocks" :serializers="serializers" />

and then add the serializer code:

const serializers = {
  types: {
    image: (data) => {
      return h("img", { src: imageUrlFor(data).width(400).url() });
    },
  },
};

Remember to export this along with the blocks.

You can grab the h component from vue:

import { h } from "vue";
  • Related