You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt3中创建highlight.js插件并在组件中使用?

解决Nuxt3中highlight.js代码高亮插件的问题

问题分析

  • 直接将hljs作为Vue插件注册是错误的,原生highlight.js没有提供Vue插件接口,需要使用官方适配的Vue3插件
  • 插件中重复导入两个样式文件,会导致样式冲突
  • 组件模板中使用的myCode变量与script里定义的code变量名称不一致

解决方案

1. 安装必要依赖

先安装highlight.js和官方Vue3插件:

npm install highlight.js @highlightjs/vue-plugin

2. 修改插件文件 @/plugins/highlight.js

替换原代码为:

// @/plugins/highlight.js
import hljs from 'highlight.js/lib/core'
import json from 'highlight.js/lib/languages/json'
import 'highlight.js/styles/vs.css' // 保留一个样式文件即可
import hljsVuePlugin from '@highlightjs/vue-plugin'

hljs.registerLanguage('json', json)

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(hljsVuePlugin)
})

3. 修正组件 @/components/JSONView.vue

将模板中的myCode改为code,与script里的变量名保持一致:

// @/components/JSONView.vue
<template>
  <highlightjs
    language="json"
    :code="code"
   />
</template>

<script setup>
import { ref } from 'vue'

const code = ref('{ "done": true }')
</script>

4. 验证使用

在页面或其他组件中引入JSONView组件即可看到代码高亮效果:

<template>
  <JSONView />
</template>

<script setup>
import JSONView from '@/components/JSONView.vue'
</script>

内容的提问来源于stack exchange,提问作者felixleo22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:52:52