1.依赖showdown.js
npm i showdown
import showdown from 'showdown'
converter = new showdown.Converter(),
text = '# hello, markdown!',
html = converter.makeHtml(text);
1-1.话不多说直接贴代码,我这里用的是bootstrap样式
<template>
<div class="container">
<div class="row">
<div class="text-center alert-danger alert alert-dismissible" v-show="message">
<span>{{message}}</span>
</div>
</div>
<form @submit.prevent="Create">
<div class="row">
<div class="col-sm-11 col-xs-9">
<input type="text" class="form-control" required placeholder="输入标题" v-model="formData.title" minlength="3" maxlength="100" @input="Checktitle">
</div>
<div class="col-sm-1 col-xs-1">
<button type="submit" class="btn btn-success">发表</button>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-6 col-xs-12">
<div class="edit" contenteditable autofocus v-focus v-text="content" @input="CheckContent">
</div>
</div>
<div class="col-xs-6 hidden-xs">
<div id="show-content" v-html='htmlStr' v-highlight></div>
</div>
</div>
</form>
<br>
</div>
</template>
<script>
export default {
data() {
return {
formData: {
title: '',
content: '',
},
converter: null,
htmlStr: '',
message: ""
}
},
mounted() { this.init() },
methods: {
init() {
this.converter = new showdown.Converter()
},
CheckContent($event) {
this.formData.content = $event.target.innerText
this.formData.content = this.formData.content.substring(0, 10000)
this.htmlStr = this.converter.makeHtml(this.formData.content)
},
Checktitle() {
this.formData.title = this.formData.title.substring(0, 100)
},
Create: _.debounce(async function() {
if (!this.formData.title) {
return this.message = "标题不能为空"
}
if (!this.formData.content) {
return this.message = "话题不能为空"
}
this.message = ""
}, 500)
}
}
</script>
<style>
#show-content {
padding: 10px;
border: 1px solid darkgray;
min-height: 600px;
}
.edit {
padding: 10px;
border: 1px solid darkgray;
min-height: 600px;
font-size: 24px;
color: #666363;
}
pre {
padding: 3px;
}
.alert_msg {
position: fixed;
width: 200px;
margin: 0 auto;
bottom: 60px;
}
</style>
1-2.高亮显示
npm i highlight.js
import hljs from 'highlight.js'
import 'highlight.js/styles/googlecode.css'
- 注册全局自定义组件
Vue.directive('highlight',function (el) {
let blocks = el.querySelectorAll('pre code');
blocks.forEach((block)=>{
hljs.highlightBlock(block)
})
})
- 自动聚焦 div可编辑后容易失去焦点,具体百度一下
Vue.directive('focus', {
inserted: function(el) {
el.focus()
}
})