利用markdown模块 自制效果及属性
其中加了一个展示区可看和不可看功能preview
步骤 :
- 搭建好对应的静态样式
- 下载markdown 模块
npm i markdown -S
(这里是局部下载) - 利用@input方法中的e
- e.target.innerText获取输入的内容
- markdown.toHtml(获取的内容)----转成markdown格式
- 标签上添加v-html=“html”
代码如下
markdown 组件
<template>
<div class="markdown">
<div class="edit"
@input="input"
contenteditable></div>
<div class="show" id="show" v-html="html" v-if="preview"></div>
</div>
</template>
<script>
//引入模块
import markdown from 'markdown'
//将模块命名
const { markdown: md } = markdown
export default {
props: {
preview: Boolean
},
data () {
return {
html: ""
}
},
methods: {
input(e) {
const text = e.target.innerText
if(this.preview) {
this.html = md.toHTML(text)
}
this.$emit("content-change",text)
}
}
}
</script>
<style>
.markdown {
height: 500px;
display: flex;
background-color: #ffffff;
}
.edit, .show {
box-sizing: border-box;
width: 50%;
flex-shrink: 0;
overflow: auto;
}
.edit {
outline: none;
padding: 20px 20px 20px 0;
}
.show {
padding: 20px 0 20px 20px;
border-left: 1px solid #f0f0f0;
}
.show h1 {font-size: 32px; font-weight: bold; color: #000;}
</style>
markdown的父组件 (下面的请求过程可以不看)
<template>
<div>
<!-- 标题 -->
<div class="title">
<input type="text" v-model="question.title" placeholder="请在此输入标题">
</div>
<!-- 描述 -->
<div class="desc">
<textarea type="text" v-model="question.desc"
placeholder="请输入问题描述"
></textarea>
</div>
<!-- Markdown内容 -->
<Markdown preview @content-change="contentChange"></Markdown>
<!-- 新增按钮 -->
<div class="btn">
<el-button type="primary" @click="add">
新增
</el-button>
</div>
</div>
</template>
<script>
import Markdown from '@/components/Markdown'
import { POST_QUESTION } from "@/service/questions"
export default {
data() {
return {
question: {
title: "",
desc: "",
answer: ""
}
}
},
components:{
Markdown
},
methods: {
contentChange(text){
console.log(text);
},
add(){
POST_QUESTION(this.question).then(res=>{
console.log(res);
this.$message.success("添加成功")
this.$router.push("/")
})
}
}
};
</script>
<style scoped>
input, textarea {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
}
.title, .desc {
width: 100%;
border-bottom: 1px solid #f0f0f0;
}
.title input {
padding-bottom: 10px;
border: none;
background: #fff;
outline: none;
font-size: 16px;
font-weight: bold;
width: 100%;
height: 30px;
}
.title input::-webkit-input-placeholder {
color: #ddd;
font-size: 16px;
font-weight: bold;
}
.desc textarea{
resize: none;
border: none;
outline: none;
width: 100%;
height: 100px;
/* margin-top: 20px; */
padding: 10px 0;
font-size: 16px;
}
.btn{
position: absolute;
top: 9px;
right: 158px;
}
</style>