前言
此文记录Nuxt引入mavon-editor + 使用 + markdown语法渲染。可用于个人博客、论坛等项目
mavon-editor
介绍
mavon-editor是一款基于Vue的markdown编辑器
项目开源地址:github.com/hinesboy/ma… (很有借鉴意义,看了以后自己也想整一个)
Nuxt引入方法
官方文档中有说明,基本步骤如下:
npm install mavon-editor --save
- 在工程目录plugins 下新建 mavon-editor.js
plugins/mavon-editor.js
import Vue from 'vue'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
Vue.use(mavonEditor)
- 在nuxt.config.js 中添加plugins配置
plugins: [
{src: '~plugins/mavon-editor', ssr: false},
],
- 在页面或者组件中引入
<v-container fluid>
<mavon-editor :toolbars="markdownOption" v-model="post.content" style="width: 100%; height: 800px;"
:ishljs="true" @change="updateDoc" @save="saveDoc"/>
</v-container>
data(){
return {
markdownOption: {
bold: true, // 粗体
italic: true, // 斜体
header: true, // 标题
underline: true, // 下划线
strikethrough: true, // 中划线
mark: true, // 标记
// superscript: true, // 上角标
// subscript: true, // 下角标
quote: true, // 引用
ol: true, // 有序列表
ul: true, // 无序列表
link: true, // 链接
// imagelink: true, // 图片链接
code: true, // code
table: true, // 表格
fullscreen: false, // 全屏编辑
readmodel: false, // 沉浸式阅读
htmlcode: true, // 展示html源码
help: true, // 帮助
undo: true, // 上一步
redo: true, // 下一步
trash: true, // 清空
save: true, // 保存(触发events中的save事件)
navigation: true, // 导航目录
alignleft: true, // 左对齐
aligncenter: true, // 居中
alignright: true, // 右对齐
subfield: true, // 单双栏模式
preview: true, // 预览
},
post: {
content: "",
html: "",
},
}
}
使用效果如下:
如果想要代码关键词高亮,可考虑引入highlight.js,笔者这里暂时忽略
mardown渲染
- 将变更绑定到这两个函数:
methods: {
updateDoc(markdown, render) {
this.html = render;
this.markdown = markdown;
},
saveDoc(markdown, render) {
this.html = render;
this.markdown = markdown;
},
}
其中html为代码部分,如下图所示:
markdown为文字部分,即左边的编辑框中用户输入部分。
-
将这两部分分别上传至服务端。
-
在需要渲染的界面请求数据并使用v-html标签:
<v-card-text v-html="content" class="markdown-body">
</v-card-text>
渲染效果如下: