如题,我们在Vue里实现MarkDown编辑器,相对于富文本,MarkDown更加的方便快捷,所以就有了这篇文章,可以让我们在vue里面使用MarkDown编辑器编辑排版文本内容
做好之后的效果图(MarkDown编辑器支持vue的不少,我这里仅供参考)
接下来讲解下如何安装配置这个MarkDown编辑器
首先安装 markdown 编辑器
npm install zx-markdown-editor
安装完成之后,新建位置存放markdown js脚本,js脚本和vue需要在同级目录
这是楼主的目录结构,具体目录结构可以查看代码部分,或者自定义目录位置
vabMarkdownEditor.JS 脚本内容
import ZxMarkdownEditor from "./markdown";
export default ZxMarkdownEditor;
if (typeof window !== "undefined" && window.Vue) {
window.Vue.component("zx-markdown-editor", ZxMarkdownEditor);
}
这里是属于MarkDown的编辑配置部分
markdown.vue的脚本部分
<template>
<div class="simple-mde" :class="classes">
<textarea ref="mde"></textarea>
</div>
</template>
<script>
import "font-awesome/css/font-awesome.min.css";
import SimpleMDE from "simplemde";
import "simplemde/dist/simplemde.min.css";
import marked from "marked";
import "github-markdown-css/github-markdown.css";
export default {
name: "markdown",
props: {
value: {
type: String,
default: "",
},
border: {
type: Boolean,
default: false,
},
config: {
type: Object,
default: () => ({}),
},
},
data() {
return {
mde: null,
defaultConfig: {},
};
},
computed: {
classes() {
return [
{
"i-mde-no-border": !this.border,
},
];
},
},
mounted() {
this.init();
},
beforeDestroy() {
this.mde = null;
},
methods: {
init() {
const config = Object.assign({}, this.defaultConfig, this.config);
this.mde = new SimpleMDE({
...config,
initialValue: this.value,
element: this.$refs.mde,
autoDownloadFontAwesome: false,
});
this.mde.codemirror.on("change", () => {
this.$emit("input", this.mde.value());
this.$emit("on-change", this.mde.value());
const mdHtml = marked(this.mde.value() || "", {
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
});
this.$emit(
"show-html",
'<div class="markdown-body" >' + mdHtml + "</div>"
);
});
},
add(val) {
if (this.mde) {
this.mde.value(this.value + val);
}
},
replace(val) {
if (this.mde) {
this.mde.value(val);
}
},
},
};
</script>
页面代码部分,放到新建的vue页面,或者是嵌入具体的页面位置
<template>
<div class="markdown-editor-container">
<el-row :gutter="20">
<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
<vab-markdown-editor
ref="mde"
v-model="value"
@show-html="handleShowHtml"
></vab-markdown-editor>
</el-col>
<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
<el-card shadow="hover">
<div slot="header">
<span>实时预览部分</span>
</div>
<div v-html="html"></div>
</el-card>
</el-col>
</el-row>
</div>
</template>
<script>
//这里引入我们的js文件,路径可以自定义
import VabMarkdownEditor from "../../components/markdown/vabMarkdownEditor";
export default {
name: "markDown",
components: { VabMarkdownEditor },
data() {
return {
//上班是用来编辑的内容,下边是实时预览的信息值
value: "# vue-admin-beautiful",
html: '<h1 id="vue-admin-beautiful">vue-admin-beautiful</h1>',
};
},
methods: {
//用来把编写的文本内容实时转换到右侧的显示区域
handleShowHtml(html) {
this.html = html;
},
},
};
</script>