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

Syntax highlighting on dynamic blog posts not working

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

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

editorData 只是一个字符串。在显示博客 post 的页面上,我从服务器抓取博客 post 并将其显示在 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>

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

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

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

P.S。必须有更好的方法来创建一个管理面板,我可以在其中创建博客 posts,当我键入代码时,它会以语法高亮显示。我试了一下 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 modified from 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>