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.
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.
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 :)
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>
v-html. Could be that too. My interpretation was that he wanted to mimic how VueJS displays their code. However, if he wants to display code it would definitely be more user friendly to also syntax highlight it - even if this wasn't his question to begin with.