How to import PortableText in Vue.js
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/vueBasic 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.
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.