Vue.js Syntax Highlighting with highlight.js

vue-highlightjs Syntax highlighting with highlight.js for Vue.js 2.x. See how to use highlight.js for syntax highlighting in a Vue application, using a simple v-highlightjs directive. You can see a live example here. Example


vue-highlightjs

Syntax highlighting with highlight.js for Vue.js 2.x. See how to use highlight.js for syntax highlighting in a Vue application, using a simple v-highlightjs directive. You can see a live example here.

Example

Installation
npm install --save highlight.js
Usage
<!-- Use the stylesheet from the CDN -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/default.min.css">
main.js
import hljs from 'highlight.js'

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.innerHTML = 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.innerHTML = binding.value
        hljs.highlightBlock(target)
      }
    })
  }
})
You can also use the npm package vue-highlightjs instead of declaring the directive manually. App.vue
<pre v-highlightjs><code class="javascript">// 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>
methods: {
    updateSourceCode: function() {
        this.sourcecode = 'const str = "' + new Date() + '"'
    }
}
The code available here. Created by @metachris
http://platform.twitter.com/widgets.js

Source link

Tags :