Vue中使用WangEditor富文本编辑框实现文本编辑与展示

在Web开发过程中,富文本编辑器是一个非常重要的功能。本文将介绍如何在Vue项目中集成WangEditor富文本编辑框,实现文本编辑并在页面上展示。

一、WangEditor简介

WangEditor是一款基于JavaScript开发的富文本编辑器,具有轻量级、易用性等优点。它支持多种格式文本编辑,如标题、段落、列表、图片、视频等,非常适合用于博客、论坛、在线文档等场景。

二、准备工作

在开始集成WangEditor之前,请确保您的项目中已安装Vue。以下是本文所需的环境和依赖:

  1. Node.js
  2. Vue CLI
  3. WangEditor(版本:^4.7.0)

三、集成WangEditor

1、安装WangEditor

在项目根目录下,运行以下命令安装WangEditor:

bash 复制代码
npm install wangeditor --save

2、选项式API中使用WangEditor

在选项式API中,我们通常会在组件的mounted钩子中初始化WangEditor,并在methods中定义相关的方法。

javascript 复制代码
<template>
  <div>
    <div ref="editor" style="text-align:left;"></div>
    <button @click="getContent">获取内容</button>
    <div v-html="editorContent" style="border:1px solid #ccc; margin-top:10px; padding:10px;"></div>
  </div>
</template>

<script>
import E from 'wangeditor'

export default {
  name: 'WangEditor',
  data() {
    return {
      editor: null,
      editorContent: ''
    }
  },
  mounted() {
    this.initEditor()
  },
  methods: {
    initEditor() {
      this.editor = new E(this.$refs.editor)
      this.editor.customConfig.onchange = (html) => {
        this.editorContent = html
      }
      this.editor.create()
    },
    getContent() {
      console.log(this.editorContent)
    }
  }
}
</script>

3、组合式API中使用WangEditor

在组合式API中,我们使用setup函数来组织代码。setup函数是Vue 3中的新特性,它运行在组件的生命周期之前,是组件的入口。

javascript 复制代码
<template>
  <div>
    <div ref="editorRef" style="text-align:left;"></div>
    <button @click="getContent">获取内容</button>
    <div v-html="editorContent" style="border:1px solid #ccc; margin-top:10px; padding:10px;"></div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import E from 'wangeditor'

export default {
  name: 'WangEditor',
  setup() {
    const editorRef = ref(null)
    const editorContent = ref('')

    const initEditor = () => {
      const editor = new E(editorRef.value)
      editor.customConfig.onchange = (html) => {
        editorContent.value = html
      }
      editor.create()
    }

    const getContent = () => {
      console.log(editorContent.value)
    }

    onMounted(() => {
      initEditor()
    })

    return {
      editorRef,
      editorContent,
      getContent
    }
  }
}
</script>

在组合式API中,我们使用ref来定义响应式数据,并使用onMounted生命周期钩子来初始化编辑器。setup函数返回的对象中的属性和方法都可以在模板中直接使用。

本文介绍了在Vue项目中集成WangEditor富文本编辑框的方法,通过简单的步骤实现了文本编辑与展示。希望对您在开发过程中有所帮助。如有疑问,请随时提问。

相关推荐
zhanshuo2 分钟前
不依赖框架,如何用 JS 实现一个完整的前端路由系统
前端·javascript·html
火柴盒zhang3 分钟前
websheet在线电子表格(spreadsheet)在集团型企业财务报表中的应用
前端·html·报表·合并·spreadsheet·websheet·集团财务
讨厌吃蛋黄酥3 分钟前
智能前端新纪元:语音交互技术与安全实践全解析
javascript
khalil5 分钟前
基于 Vue3实现一款简历生成工具
前端·vue.js
拾光拾趣录12 分钟前
浏览器对队头阻塞问题的深度优化策略
前端·浏览器
用户81221993672212 分钟前
[已完结]后端开发必备高阶技能--自研企业级网关组件(Netty+Nacos+Disruptor)
前端
万少17 分钟前
2025中了 聊一聊程序员为什么都要做自己的产品
前端·harmonyos
1234Wu31 分钟前
React Native 接入 eCharts
javascript·react native·react.js
abigale032 小时前
webpack+vite前端构建工具 -11实战中的配置技巧
前端·webpack·node.js
专注API从业者3 小时前
构建淘宝评论监控系统:API 接口开发与实时数据采集教程
大数据·前端·数据库·oracle