vue wangeditor富文本編輯器

wangeditor 是一款輕量級的富文本編輯器,在個人我的博客項目中用到了它,這裏作一個記錄。html

官方地址:地址npm

安裝:npm install wangeditor --save編輯器

在component 目錄中建立 wangEditor文件夾ide

image.png

在 wangEditor 文件夾中建立 index.js 文件this

index.js中的內容spa

<template>
  <div ref="editor"></div>
</template>

<script>
import E from 'wangeditor'
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    meanArray: {
      // 自定義菜單
      type: Array,
      default: null
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  watch: {
    value: function (value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value)
      }
    }
    // value爲編輯框輸入的內容,這裏我監聽了一下值,當父組件調用得時候,若是給value賦值了,子組件將會顯示父組件賦給的值
  },
  data () {
    return {
      // 默認有這麼多菜單,meanArray有值以meanArray爲準
      defaultMeanus: [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo'
      ],
      editor: ''
    }
  },
  methods: {
    init () {
      const _this = this
      this.editor = new E(this.$refs.editor)
      this.editor.config.uploadImgShowBase64 = true // 使用 base64 保存圖片
      this.setMenus() // 設置菜單
      this.editor.config.onchange = (html) => {
        _this.$emit('change', html) // 將內容同步到父組件中
      }
      this.editor.create() // 建立編輯器
    },
    setMenus () {
      // 設置菜單
      if (this.meanArray) {
        this.editor.config.menus = this.meanArray
      } else {
        this.editor.config.menus = this.defaultMeanus
      }
    },
    getHtml () {
      // 獲得文本內容
      return this.editor.txt.html()
    },
    setHtml (txt) {
      // 設置富文本里面的值
      this.editor.txt.html(txt)
    }
  },
  mounted () {
    const that = this
    that.$nextTick(function () {
      that.init()
    })
  }
}
</script>

在父組件中調用code

<template>
 <!-- 富文本編輯器 -->
 <!-- ref 不一樣能夠實現多個富文本編輯器 -->
 <editor ref="editorOne" v-model="detail" @change="change"></editor>
</template>

<script>
import Editor from '@/components/wangEditor'

export default {
  data () {
    return {
      // 文章內容
      detail: ''
    }
  }
  methods: {
    change (val) {
      // console.log(val)
      // console.log(this.detail)
    }
  components: { Editor }
}
</script>
相關文章
相關標籤/搜索