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

Laravel10+Vue3使用vue-code-highlight报错‘g._self is undefined’的解决方法

解决Laravel 10+Vue3中代码高亮组件的TypeError: g._self is undefined问题

问题原因

你遇到的TypeError: g._self is undefined错误,是因为vue-code-highlight组件大概率是为Vue2设计的,内部使用了Vue2特有的实例属性_self,而Vue3的组合式API(尤其是<script setup>)中不存在该属性,导致兼容性冲突。

解决方案

方案1:修复vue-code-highlight的使用(若坚持使用该组件)

  • 移除不必要的defineExpose:你当前代码中的defineExpose({ VueCodeHighlight })完全多余,组件无需暴露给父组件即可在自身模板使用。
  • 修正模板用法:组件本身会生成<pre>和<code>标签,无需手动嵌套<pre>,否则会导致结构冗余和潜在渲染问题。
  • 全局注册组件(规避<script setup>兼容性问题):在Vue3的全局配置文件(比如resources/js/app.js)中注册组件,而非在单个组件内导入:
    import { createApp } from 'vue';
    import { component as VueCodeHighlight } from 'vue-code-highlight';
    import 'vue-code-highlight/themes/prism-tomorrow.css'; // 导入你需要的主题样式
    
    const app = createApp({});
    app.component('VueCodeHighlight', VueCodeHighlight);
    // 其他全局配置...
    app.mount('#app');
    
    之后在组件模板中直接使用:
    <VueCodeHighlight language="javascript">
      let x = 3;
    </VueCodeHighlight>
    

方案2:替换为Vue3兼容的代码高亮组件(更推荐)

由于vue-code-highlight对Vue3的支持不完善,建议替换为以下成熟组件:

选项A:使用vue-prism-component

  1. 安装依赖:
    npm install prismjs vue-prism-component
    
  2. 组件内使用:
    <script setup>
    // 其他导入...
    import Prism from 'prismjs';
    import 'prismjs/themes/prism-tomorrow.css'; // 选择主题样式
    import PrismComponent from 'vue-prism-component';
    </script>
    
    <template>
      <BlogLayout>
        <Head title="Home" />
        <div class="container-screen">
          <div class="content">
            <div class="post">
              Post 1
              <prism language="javascript">
                let x = 3;
              </prism>
            </div>
          </div>
        </div>
      </BlogLayout>
    </template>
    

选项B:使用vue-highlightjs

  1. 安装依赖:
    npm install vue-highlightjs highlight.js
    
  2. 组件内使用:
    <script setup>
    // 其他导入...
    import VueHighlightJS from 'vue-highlightjs';
    import 'highlight.js/styles/github.css'; // 选择主题样式
    </script>
    
    <template>
      <BlogLayout>
        <Head title="Home" />
        <div class="container-screen">
          <div class="content">
            <div class="post">
              Post 1
              <highlight-code language="javascript">
                let x = 3;
              </highlight-code>
            </div>
          </div>
        </div>
      </BlogLayout>
    </template>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:36:01