Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting.
Vue has many markdown parsing libraries, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library.
Open the command window under the vue project and enter the following command
npm install marked -save // marked 用于将markdown转换成html npm install highlight.js -save //用于代码高亮显示
The command is executed You can then see the installed version number in the console or package.json file
import hljs from 'highlight.js'; import 'highlight.js/styles/atom-one-dark.css' //样式 //创建v-highlight全局指令 Vue.directive('highlight',function (el) { let blocks = el.querySelectorAll('pre code'); blocks.forEach((block)=>{ hljs.highlightBlock(block) }) })
This way you can use v-highlight to reference the code highlighting method in the vue component.
The code examples are as follows:
markdown parsing and Code highlighting effect
The style referenced in the example isimport 'highlight.js/styles/atom-one-dark.css'
Actually highlight.js/styles provides many styles, which can be selected according to your own preferences.
The above is the detailed content of How Vue3 parses markdown and implements code highlighting. For more information, please follow other related articles on the PHP Chinese website!