imnhasan
imnhasan

Reputation: 115

How do I do syntax highlighting in VueJS

enter image description here

How do I display syntax-highlighted HTML code like this picture from the VueJS documentation?

I have tried using v-html but I just get a console error.

Upvotes: 0

Views: 7780

Answers (3)

Muhammad Ichsan
Muhammad Ichsan

Reputation: 425

If you use vue 3 I recommend you to use this package https://www.npmjs.com/package/vue-code-highlighter

It's a modern vue syntax highlighter made by me :)

Upvotes: 2

muka.gergely
muka.gergely

Reputation: 8329

You could just put out the sanitized string:

new Vue({
  el: "#app",
  data() {
    return {
      script: `<script src="https://unpkg.com/vue@next"></script>`,
    }
  },
  template: `
    <div>
      Code:<br>
      <code v-html="script"></code><br>
    </div>
  `,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Upvotes: 1

Jordan
Jordan

Reputation: 2371

Upon inspecting the VueJS documentation code snips, you can see they contain the class hljs.

This class is used by HighlightJS, a simple framework for code syntax highlighting.

HighlightJS automatically detects the language based on the syntax and can be extended with custom themes and configurations.

To install it in your vue package simply run either npm install highlight.js --save or yarn add highlight.js.

Once installed, import it and register it as a Vue plugin Vue.use(hljs.vuePlugin);

You can then use the component within your Vue templates:

<div id="app">
    <!-- bind to a data property named `code` -->
    <highlightjs autodetect :code="code" />
    <!-- or literal code works as well -->
    <highlightjs language='javascript' code="var x = 5;" />
</div>

You can find the above Vue example here in the documentation.

Upvotes: 2

Related Questions