給vue添加一個超級好用的富文本編輯器 markdown

用過百度富文本編輯器ueditor,還用過Ttinymce編輯器,都感受很通常,最近看到一個超級好用的富文本,除了普通富文本的這些功能,還能夠直接在編輯器上輸入代碼來寫頁面。左邊寫內容,右邊看效果,也就是至關於可視化編輯器。css

好了,廢話很少說,直接開始吧。html

 首先第一步確定是安裝了:vue

  命令行工具輸入: npm install mavon-editor --saveios

 第二步,引入markdown組件 和 註冊markdown組件npm

  引入:axios

    import {mavonEditor} from "mavon-editor";服務器

    import "mavon-editor/dist/css/index.css";markdown

  註冊:app

    components: {mavonEditor},編輯器

 

  具體步驟看下圖

  

 

 

 

 第三步,使用:

<template> <div> <!-- @save: 按下 ctrl + s 時觸發 @change: 當值發生改變時 觸發 --> <mavon-editor @save="saveDoc" @change="updateDoc" ref="editor" v-model="doc"> </mavon-editor> </div> </template> <script> import { mavonEditor } from "mavon-editor"; import "mavon-editor/dist/css/index.css"; export default { name: "Create", components: { mavonEditor }, data() { return { doc: "" }; }, methods: { updateDoc(markdown, html) { // 此時會自動將 markdown 和 html 傳遞到這個方法中 console.log("markdown內容: " + markdown); console.log("html內容:" + markdown); }, saveDoc(markdown, html) { // 此時會自動將 markdown 和 html 傳遞到這個方法中 console.log("markdown內容:" + markdown); console.log("html內容:" + html); } } }; </script>

  

 

 

  效果展現:

  

 

  接下來是修改和獲取值: 

  // 獲取 markdown

  let markdown = this.$refs.editor.d_value;

 

 // 修改 markdown
  
 this.$refs.editor.d_value = '> hello world';
 
// 獲取編譯後的 html

 let html = this.$refs.editor.d_render;

注意,通常都是使用 this.$refs這樣的方式來獲取或修改數據,若是隻使用this則只能獲取到markdown和修改
this.$refs這樣的方式來獲取或修改數據,若是隻使用this則只能獲取到markdown和修改markdown和修改markdown獲取不到編譯後的html

 附:
markdown獲取不到編譯後的html

 附:

 

  若是以爲在每一個頁面都要引入註冊麻煩,那也能夠直接掛載在vue的原型上。

  在main.js 裏面 引入組件而且掛載到vue原型上,如圖: 這樣就不須要再在頁面引入而且註冊了,直接在使用頁面使用 標籤<mavon-editor> </mavon-editor> 便可以能夠開始使用了

  

 

  最後,配置把圖片上傳到服務器: 

  <template>
    <mavon-editor ref=md @imgAdd="$imgAdd" @imgDel="$imgDel"></mavon-editor>
  </template>
  exports default {
    methods: {
      // 綁定@imgAdd event
      $imgAdd(pos, $file){
        // 第一步.將圖片上傳到服務器.
        var formdata = new FormData();
        formdata.append('image', $file);
        axios({
          url: 'server url',
          method: 'post',
          data: formdata,
          headers: { 'Content-Type': 'multipart/form-data' },
        }).then((url) => {
          // 第二步.將返回的url替換到文本原位置![...](0) -> ![...](url)
          /**
            * $vm 指爲mavonEditor實例,能夠經過以下兩種方式獲取
            * 1. 經過引入對象獲取: `import {mavonEditor} from ...` 等方式引入後,`$vm`爲`mavonEditor`
            * 2. 經過$refs獲取: html聲明ref : `<mavon-editor ref=md ></mavon-editor>,`$vm`爲 `this.$refs.md`
          */
          $vm.$img2Url(pos, url);
        })
      }
    }
  }

相關文章
相關標籤/搜索