web文本编辑 markdown 富文本

350 阅读1分钟

1.markdown编辑器

<template>
  <div>
    <div class="write-btn">
      <el-button @click="submit" type='primary'>提交</el-button>
    </div>
    <el-row>
      <el-col :span='12'>
        <textarea ref="editor" class="md-editor" :value="content" @input="update" ></textarea>
      </el-col>
      <el-col :span='12'>
        <div class="markdown-body" v-html="compiledContent"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import marked from 'marked'
import hljs from 'highlight.js'
//引入md支持 ```javascript 的写法
import javascript from 'highlight.js/lib/languages/javascript'
//引入js高亮的样式
import 'highlight.js/styles/monokai-sublime.css'
// monokai-sublime
export default {
  data(){
    return {
      // timer:
      content:`# 标题:${String(Math.random()).slice(2,6)} 
      
\`\`\`javascript
  //这里的代码会变成高亮
  let a =1;
  console.log(a)
\`\`\`
      `
      
      `
    }
  },
  mounted(){
    this.timer = null
    this.bindEvents()
    marked.setOptions({
      rendered: new marked.Renderer(),
      highlight(code){
        //代码添加高亮效果
        return hljs.highlightAuto(code).value
      }
    })
  },
  computed:{
    compiledContent(){
      return marked(this.content, {})
    }
  },

  methods:{
    bindEvents(){
      //复制粘贴方式
      this.$refs.editor.addEventListener('paste',async e=>{
        const files = e.clipboardData.files
        console.log(files)
        // 直接上传
      })
      //直接拖拽方式上传
      this.$refs.editor.addEventListener('drop', async e=>{
        const files = e.dataTransfer.files
        console.log(files)
        // @todo 文件上传
        e.preventDefault()//阻止默认事件
      })
    },
    update(e){//添加防抖控制
      clearTimeout(this.timer)
      this.timer = setTimeout(()=>{
        this.content = e.target.value
      },350)
    },
    async submit(){
       
    }
  }
}
</script>

<style> 
.md-editor{
  width:100%;
  height:100vh;
  outline: none;
}
.write-btn{
  position: fixed;
  z-index:100;
  right:30px;
  top:10px;
}
</style>

富文本编辑器实现

1.div 设置contenteditable="true"

    <div contenteditable="true">666 标题1111</div>
    document.execCommand('SelectAll') //选中整个文档。 
    document.execCommand('Undo') //取消操作

2.第三方库 tinyMce,wangEditor

3.使用开源的定制 slate.js

4.自己实现,在线word