最新nuxt3使用highlight.js高亮

445 阅读1分钟

"highlight.js": "^11.7.0",

plugins 注册指令highlight

在 根目录 plugins/global.ts 中注册组件

import Hljs from 'highlight.js'

export default defineNuxtPlugin(async NuxtApp => {
  // nuxtApp包含的属性可看文档 https://nuxt.com/docs/guide/going-further/internals
  
  NuxtApp.vueApp.directive('highlight', function (el) {
    const blocks = el.querySelectorAll('pre code')
    blocks.forEach((block: any) => {
      Hljs.highlightBlock(block)
    })
  })
})

封装组件 CodeView

在components下封装CodeView.vue

<template>
  <div v-highlight>
    <pre>
        <code>{{ props.code }}</code>
    </pre>
  </div>
</template>
<script setup lang="ts">
import 'highlight.js/styles/default.css'
const props = defineProps(['code'])
</script>

其他页面调用

<CodeView :code="code" />