Vue.js syntax highlighting with highlight.js
https://www.metachris.com/2017/02/vuejs-syntax-highlighting-with-highlightjs/
HTML
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<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>
<div id="app">
<pre v-highlightjs><code class="python">// Static source code
function(test) {
console.log(test)
}</code></pre>
<pre v-highlightjs="sourcecode"><code class="javascript"></code></pre>
<button @click="updateSourceCode">Update source code</button>
</div>
JavaScript
Vue.directive('highlightjs', {
deep: true,
bind: function(el, binding) {
// on first bind, highlight all targets
let targets = el.querySelectorAll('code')
targets.forEach((target) => {
// if a value is directly assigned to the directive, use this
// instead of the element content.
if (binding.value) {
target.textContent = binding.value
}
hljs.highlightBlock(target)
})
},
componentUpdated: function(el, binding) {
// after an update, re-fill the content and then highlight
let targets = el.querySelectorAll('code')
targets.forEach((target) => {
if (binding.value) {
target.textContent = binding.value
hljs.highlightBlock(target)
}
})
}
})
new Vue({
el: '#app',
data: {
sourcecode: 'const str = "This sourcecode will update dynamically"'
},
methods: {
updateSourceCode: function() {
this.sourcecode = '<b>const str = "' + new Date() + '"</b>'
}
}
})