javascript - 动态博客文章上的语法突出显示不起作用

标签 javascript vue.js highlight.js

我正在使用 Vue 创建博客并使用 vue-highlightjs为我将在博客文章中编写的代码添加语法突出显示。我只是在使用 textarea在我的管理面板中编写博客文章,所以我必须手动输入我想要显示的 HTML。

<textarea v-model="editorData" cols="60" rows="10"></textarea>

editorData只是一个字符串。在显示博文的页面上,我从服务器抓取博文并将其显示在 BlogPost.vue 组件中。这是该组件的代码:

<template>
  <div>
    <pre v-highlightjs><code class="javascript">const s = new Date().toString()</code></pre>
    <h1 class="page-title">{{postTitle}}</h1>
    <div v-html="postBody"></div>
  </div>
</template>

<script>
import axios from "axios";
import { baseUrl } from "@/strings";
export default {
  name: "BlogPost",
  data: function() {
    return {
      postTitle: "",
      postBody: ""
    };
  },

  beforeRouteEnter(to, from, next) {
    axios.get(baseUrl + "/blogPosts/" + to.params.id).then(response => {
      next(vm => vm.setData(response.data));
    });
  },
  methods: {
    setData(data) {
      this.postTitle = data.title;
      this.postBody = data.content;
    }
  }
};
</script>

v-highlightjs pre 中的指令模板开头的标签只是告诉 vue-highlightjs 插件为里面的代码添加语法高亮。

问题是 pre 中的硬编码代码div开头的标签突出显示,但动态加载的代码在 postBody未突出显示。例如,如果我输入 <pre v-highlightjs><code class="javascript">const s = new Date().toString()</code></pre>进入我的管理面板文本区域,然后在我的 BlogPost.vue 页面中显示帖子,它看起来像这样:

enter image description here

不知道是vue-highlightjs不高亮代码是因为它是动态的还是什么。有任何想法吗?提前谢谢你。

附言必须有更好的方法来创建一个管理面板,我可以在其中制作博客文章,当我键入代码时,这些文章会以语法高亮显示。我试了一下 CKEditor,但发现它真的很困惑。有什么建议吗?

最佳答案

该指令不会在初始突出显示后突出显示更新的代码。为此,您需要将变量传递给 v-highlightjs指令:

<pre v-highlightjs="postBody"><code class="javascript"></code></pre>

来自 Vue.js Syntax Highlighting with Highlight.js :

Reacting to code updates
highlight.js replaces the content of the code block. If using the directive as shown above, updating the source-code after the initial highlighting does not work anymore. To be able to update the code and highlight it again after an update, pass the variable directly into the v-highlightjs directive

这是一个有效的 jsFiddle修改自 this example .

如果您需要对突出显示的内容进行更多控制,我建议使用 highlightjs库本身而不是指令并手动调用 hljs.highlightBlock .

new Vue({
  el: '#app',
  data: () => ({
    post: null,
    posts: [
      `Phasellus luctus magna non sem fermentum, sed pulvinar ex blandit. Vestibulum id auctor neque. Etiam aliquam commodo sollicitudin. <pre><code class="javascript">var foo = bar</code></pre>Etiam cursus commodo neque, at semper dui vestibulum auctor.`,
      `Etiam non elit velit. <pre><code class="javascript">while (true) { console.log('test') }</code></pre>Vestibulum nec posuere lorem. Ut dolor ante, eleifend ut porttitor eu, faucibus non sapien.`,
      `Morbi eleifend ornare felis, vel vulputate nibh suscipit id. <pre><code class="javascript">const func = () = ({ foo: 'bar' })</code></pre>Phasellus luctus magna non sem fermentum, sed pulvinar ex blandit. Vestibulum id auctor neque. Etiam aliquam commodo sollicitudin.`
    ]
  }),
  beforeMount() {
    this.post = this.posts[0]
  },
  mounted() {
    this.highlightPost()
  },
  methods: {
    highlightPost() {
      document.querySelectorAll('code').forEach((block) => {
        hljs.highlightBlock(block)
      })
    },
    cycle() {
      const index = this.posts.indexOf(this.post)

      this.post = index === this.posts.length - 1 ? this.posts[0] : this.posts[index + 1]

      this.$nextTick(() => {
        this.highlightPost()
      })
    }
  }
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="cycle">Next Post</button>
  <p id="post-content" v-html="post"></p>
</div>

关于javascript - 动态博客文章上的语法突出显示不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000168/

相关文章:

javascript - 在 Linux 中使用 node JS 连接 Redis

r - 如何使用highlight.js突出显示所有R函数名称?

angular - highlight.js 不适用于 Angular 2

javascript - AngularJS SPA 中的 Highlight.js 不起作用

javascript - 我如何解析来自 openlibrary api 的 Json 数据? (适本地)

JavaScript 错误 : cyclic __proto__ value

javascript - 我需要 "Autolisting"函数来编辑下拉列表

vue.js - 在 Vue 2 中处理损坏的图像 url 时如何处理无限的 GET Image 请求?

vue.js - 在 vue-test-utils 中的 stub 上使用键修饰符发出 keydown 事件

javascript - vue.js 为每第 6 个循环元素插入 block