Home> Web Front-end> Vue.js> body text

How Vue3 parses markdown and implements code highlighting

王林
Release: 2023-05-20 16:16:24
forward
3568 people have browsed it

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.

The specific implementation steps are as follows:

1. Install dependent libraries

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 //用于代码高亮显示
Copy after login

The command is executed You can then see the installed version number in the console or package.json file

How Vue3 parses markdown and implements code highlighting

2. Introduce highlight.js and styles into the main.js file and create a Customized global directive

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) }) })
Copy after login

This way you can use v-highlight to reference the code highlighting method in the vue component.

3. Apply marked parsing and code highlighting in Vue components

The code examples are as follows:

 
Copy after login
Copy after login

4. Display effect

markdown parsing and Code highlighting effect

How Vue3 parses markdown and implements code highlighting

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.

How Vue3 parses markdown and implements code highlighting

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn