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富文本编辑框的方法,通过简单的步骤实现了文本编辑与展示。希望对您在开发过程中有所帮助。如有疑问,请随时提问。

相关推荐
m0_748233643 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟11 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386312 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596013 分钟前
前端代理,解决跨域问题讲解
前端
quitv18 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238127 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星28 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端
一只小姜丝3321 小时前
解决各大浏览器中http地址无权限调用麦克风摄像头问题
网络·vue.js·网络协议·http