How to import PortableText in Vue.js

2 replies
Last updated: Apr 8, 2020
hello! Please anyone can tell me how to import PortableText in vuejs? the example below is for react. I need to import it in vue.js . thank you!
// Body.js
import React from 'react'
import PortableText from '@sanity/block-content-to-react'

AI Update

For Vue.js, you'll want to use the @portabletext/vue package instead of the React version. Here's how to import and use it:

Installation

npm install @portabletext/vue

Basic Usage in Vue 3

<script setup>
import { PortableText } from '@portabletext/vue'

const content = [
  // Your Portable Text content from Sanity
]
</script>

<template>
  <PortableText :value="content" />
</template>

With Custom Components

If you need to customize how certain blocks render (like the code example in your React snippet), you can pass custom components:

<script setup>
import { PortableText } from '@portabletext/vue'
import { h } from 'vue'

const content = [
  // Your Portable Text content
]

const components = {
  types: {
    code: ({ value }) => {
      return h('pre', { 'data-language': value.language }, [
        h('code', {}, value.code)
      ])
    }
  }
}
</script>

<template>
  <PortableText :value="content" :components="components" />
</template>

Fetching Content from Sanity

Here's a complete example with Sanity client:

<script setup>
import { ref, onMounted } from 'vue'
import { PortableText } from '@portabletext/vue'
import { createClient } from '@sanity/client'

const client = createClient({
  projectId: '<your project id>',
  dataset: '<your dataset>',
  apiVersion: '2022-05-05',
  useCdn: true
})

const content = ref(null)

onMounted(async () => {
  const article = await client.fetch('*[_type == "article"][0]')
  content.value = article.body
})
</script>

<template>
  <PortableText v-if="content" :value="content" />
</template>

Vue 2 Support

Important: @portabletext/vue is designed for Vue 3 only. If you're using Vue 2, you'll need to use the older community package sanity-blocks-vue-component, though it's not officially maintained by Sanity.

You can find more details in the official Sanity documentation on presenting Portable Text and the @portabletext/vue GitHub repository.

You’ll need to install
sanity-blocks-vue-component
and then:
import BlockContent from 'sanity-blocks-vue-component'

user R
great ! I just realised that ☺️ thank you for your reply! so it's the right way to go. Thank you! 🌈

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?