#Vue

#JavaScript

Code Highlighting

2 years ago

110

There are two major syntax-highlighting-Frameworks in the JS-World. Let's have a look at them.

Prism.js and highlight.js are both lightwight and simple and have Vue-specific implementations, that make Syntax-highlighting available through Components.

But here comes the treat: if you have user-generated content, that includes code, you usually have to utilize the v-html directive. However, v-html can't process Vue-Components for security reasons.

So we have to use the desired library directly on the content. In this case, I'm using highlight.js.

Import the styles and highlight.js:


import 'highlight.js/styles/stackoverflow-dark.css'
import hljs from 'highlight.js';

In the Vue component, as soon as the content is loaded into:


updated: function(){
	//highlight code in post.text
	var ptext=document.getElementById('ptext');
	var elements=ptext.getElementsByTagName('code');
	for (let item of elements) {
		hljs.highlightElement(item)
	}
}

Note that I'm using the update() Method here, which might be excessive in other cases.