[Vuejs]-Dynamically highlight block with highlight.js in vue app

0👍

Option 1

Use Highlight.js Vue integration (you need to setup the plugin first, check the link):

<script setup>
const props = defineProps({
  content: { type: String, required: true },
})
</script>

<template>
  <highlightjs :code="content" language="ts" />
</template>

Option 2

  • Use computed to reactively compute highlighted HTML of props.content
  • Use sync highlight(code, options) function to get the highlighted HTML
  • Use HTML as-is via innerHTML prop or v-html directive
<script setup>
import { computed } from 'vue'
import highlight from 'highlight.js'

const props = defineProps({
  content: { type: String, required: true },
})

const html = computed(() => {
  const { value } = highlight.highlight(props.content, { lang: 'ts' })
  return value
})
</script>

<template>
  <div v-html="html" />
</template>

Leave a comment