【问题标题】:Hilight JS not working with wordpress REST API and nuxtjsHilight JS 不适用于 wordpress REST API 和 nuxtjs
【发布时间】:2020-11-28 04:40:56
【问题描述】:

我正在尝试使用 highlight.js 突出显示代码,但由于某种原因它不起作用。

在我的 vue 组件上,我已经导入了 hljs

import hljs from 'highlight.js';

加载时初始化高亮

mounted: function() {
    hljs.initHighlightingOnLoad();
}

导入样式:

<style scoped>
    @import url("@/node_modules/highlight.js/styles/default.css");
    @import url("@/node_modules/highlight.js/styles/dracula.css");
</style>

要突出显示的代码将采用这种格式

<pre class="wp-block-code">
  <code class="python"> 
   def build_completion(opt_parser):
    opts_flag = []
    for group in opt_parser.option_groups:
        for option in group.option_list:
            # for every long flag
            opts_flag.append(option.get_opt_string())
    with open(BASH_COMPLETION_TEMPLATE) as f:
        template = f.read()
    with open(BASH_COMPLETION_FILE, "w") as f:
        # just using the special char
        filled_template = template.replace("{{flags}}", " ".join(opts_flag))
        f.write(filled_template)</code></pre>

还有什么方法可以在不使用类的情况下自动检测语言?

【问题讨论】:

    标签: wordpress vue.js nuxt.js


    【解决方案1】:

    highlight.js documentation 中有专门的部分介绍如何在 Vue 中使用这个库。

    首先您需要使用npm install highlight.js 安装库。

    这是一个突出显示语法的 Vue 组件示例

    <template>
      <div id="app">
        <highlightjs autodetect :code="code" />
      </div>
    </template>
    
    <script>
    import Vue from 'vue';
    import hljs from 'highlight.js';
    import 'highlight.js/styles/github.css';
    
    Vue.use(hljs.vuePlugin);
    
    export default {
      name: "App",
      data() {
        return {
          code: `
          let x = 10;
          function foo() {
            let y = 20;
          }
          `
        }
      },
    };
    </script>
    

    【讨论】:

    • 是的,它不适合我的情况,因为我的内容作为 API 中博客文章的一部分动态出现。
    • 我会逐步调试您的具体案例。首先,当调用 hljs 初始化时,我会检查所有要突出显示的 &lt;pre&gt;...&lt;/pre&gt; 内容是否已准备好并存在于 DOM 中。之后,我会检查所有 highlight.js 样式是否按预期导入。
    • 是的,在初始化hljs之前,DOM上有内容,其次所有样式都导入了。
    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2021-09-28
    • 2018-01-26
    • 2015-08-07
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多