在Vue2中封装WangEditor组件,可以按照以下步骤进行:

  1. 首先,安装WangEditor v4版本:npm install wangeditor@4.x --save

  2. 创建一个名为WangEditor.vue的文件,并编写以下代码:

<template>
  <div ref="editorRef" class="wang-editor"></div>
</template>

<script>
import WangEditor from 'wangeditor'

export default {
  name: 'WangEditor',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  mounted() {
    this.initEditor()
  },
  methods: {
    initEditor() {
      const editor = new WangEditor(this.$refs.editorRef)

      editor.config.onchange = (newHtml) => {
        this.$emit('input', newHtml)
      }

      editor.create()

      if (this.value) {
        editor.txt.html(this.value)
      }
    }
  },
  watch: {
    value(newValue) {
      const editor = WangEditor.getEditor(this.$refs.editorRef)
      editor.txt.html(newValue)
    }
  }
}
</script>

<style scoped>
.wang-editor {
  height: 400px;
}
</style>
  1. 使用封装的WangEditor组件,可以在其他组件中引入,并将数据绑定到value属性上,如下所示:
<template>
  <div>
    <wang-editor v-model="content"></wang-editor>
  </div>
</template>

<script>
import WangEditor from './WangEditor.vue'

export default {
  components: {
    WangEditor
  },
  data() {
    return {
      content: ''
    }
  }
}
</script>

在上述代码中,我们封装了一个WangEditor组件,并使用了value属性来实现双向绑定。在mounted钩子函数中,我们初始化了WangEditor实例,并通过editor.config.onchange事件监听器,将编辑器内容的变化通过$emit方法传递给父组件。同时,在watch中监听value属性的变化,并更新编辑器的内容。

这样,我们就成功封装了一个基于WangEditor v4版本的Vue2组件

vue2 封装wangeditor组件使用v4版本

原文地址: https://www.cveoy.top/t/topic/iSaE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录