Vue使用富文本wangeditor-具有双向绑定

2,170 阅读1分钟

安装

npm i wangeditor --save

使用代码

             <editor-bar
            :content.sync="form.articleBody" 向富文本子组件传值
            @editorData="changeText"> 子传父事件,第一个参数是富文本编辑器内容
            富文本插件本体
            </editor-bar>
            
          import EditorBar from '@/components/wangEnduit'
       
         // 局部注册的组件
          components: {
            EditorBar
          },
            
            // 组件状态值
              data() {
              articleBody
                return {
                  form: {}
                   }
               },    
               
           方法    
        methods: {
                changeText(val) {
                  this.articleBody = val
               }, 
          

富文本插件本体

<template>
  <div class="home">
    <div ref="demo1"></div>
  </div>
</template>

<script>
// 引入 wangEditor
import wangEditor from 'wangeditor'
export default {

  props: {
    content: {
      type: String,
      default: ''
    }
  },

  watch: {
    content() {
      this.editor.txt.html(this.content)
    }
  },

  data() {
    return {
      editor: null,
      editorData: ''
    }
  },
  mounted() {
    const editor = new wangEditor(this.$refs.demo1)
    // 配置 onchange 回调函数,将数据同步到 vue 中
    editor.config.onchange = (newHtml) => {
      this.editorData = newHtml
      this.$emit('editorData', newHtml)
    }
    editor.config.height = 200

    // 创建编辑器
    editor.create()
    this.editor = editor
  },
  methods: {
    getEditorData() {
      // 通过代码获取编辑器内容
      const data = this.editor.txt.html()
      alert(data)
    }
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy()
    this.editor = null
  }
}
</script>

<style lang="scss">
.home {
  width: 1024px;
  height: 240px;
  margin: auto;
  position: relative;
  .btn {
    position: absolute;
    right: 0;
    top: 0;
    padding: 5px 10px;
    cursor: pointer;
  }
  h3 {
    margin: 30px 0 15px;
  }
}
</style>