如何解决highlightjs在vue-router中失效的问题

通过路由切换过去的一个含有pre和code标签的页面,引入highlightjs并执行,结果页面没有任何变化,执行的时间用过afterEach,window.onload和setTimeout都实验过,页面都不会高亮代码,请问各位大神解决办法?

阅读 4.1k
1 个回答

you should not use that global init function, as it is intended to highlight all pre tags on page load, and is meant to be used on static pages.

Highlightjs offers a method for "Custom Initialization"with hljs.highlightBlock(), which you should warp in a custom directive:

// put this in the main file before you create the main instance / router.
Vue.directive('highlightjs', function() {
  hljs.highlightBlock(this.el)
}
<pre v-highlightjs>
  <!-- code to highlight-->
</pre>

So, simply add v-highlightjs to each tag that is supposed to be highlighted. That will re-highlight those tags each time Vue inserts them into the DOM (router navigation to another component etc...)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题