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:
<!-- 正文输出 --> <div class="entry-content"> <div v-highlight v-html="article" id="content"></div> </div>
<script> // 将marked 引入 import { marked }from 'marked'; export default { name: 'articles', data(){ return{ article:'' } }, methods: { getPostDetail() { console.log('getPostDetail()'+this.id) fetchPostDetail(this.id).then(res => { this.postdetail=res.data // 调用marked()方法,将markdown转换成html this.article= marked(this.postdetail.content); console.log(res.data) }).catch(err => { console.log(err) }) }, created() { //调用获取文章内容的接口方法 this.getPostDetail() }, } </script>
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!