程序员的资源宝库

网站首页 > gitee 正文

在vue项目中使用markdown编辑器及其预览并在指定页面展示内容

sanyeah 2024-04-09 20:02:04 gitee 12 ℃ 0 评论

1. 本次我们使用到的Markdown插件为mavonEditor, 好!开始:

 安装所需插件:

yarn add mavon-editor
OR
npm install mavon-editor -S

 

2. 在main.js中引入并使用:

import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

Vue.use(mavonEditor)

这里的css是不能少的(如果你想自己写样式话就没事了)。

如果还是没有样式,可以在public下的index.html文件中添加

<link href="https://cdn.bootcss.com/github-markdown-css/2.10.0/github-markdown.min.css" rel="stylesheet">

 

3. 在vue组件中使用:

<mavon-editor :value="value" @change="valueChange" />

这里绑定的change函数会在编辑输入时触发传回的params: { value: 你输入的文本, render: markdown编译之后返回的HTML文本 }

<script>
export default {
  name: "MarkDown",
  data() {
    return {
      value: "# ddd",
    };
  },
 methods: {
    valueChange(value, render) {
      //value为输入的内容,render是markdown渲染之后的html代码
      console.log(value, render);
    },
  },
}
</script>

效果图:

 

 

 

  

4. 指定页面展示编写的MD内容:

我们只需在页面组件中添加容器标签并使用v-html插入即可:

<div v-html="htmlText" class="markdown-body" />

这里的htmlText就是markdown编译之后返回的html文本内容,上方函数触发时记得保存render的值,class就是之前说的样式辣,但是注意自己是否有样式影响这里的布局,如果文本自己居中了,可以尝试在此处添加css:text-align: left。

效果:

 

 

 

 

5.  可能在使用v-html时会出现XSS警告,可以使用插件vue-dompurify-html:

安装:

yarn add vue-dompurify-html

OR

npm i vue-dompurify-html -S

在main.js中引入使用

import VueDOMPurifyHTML from 'vue-dompurify-html'

Vue.use(VueDOMPurifyHTML)

将 v-html 替换为 v-dompurify-html 。 搞定!!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表