vue中使用富文本编辑器,@tinymce/tinymce-vue

富文本就是在后台管理系统中常见的录入带格式的内容,如:表格,字体加粗,斜体,文字颜色等等,就像一个word一样。类似于这样的效果:

我们使用通用在线编辑器tinymce。支持vue和react。

1. 安装

npm i @tinymce/tinymce-vue -S

要注意版本,我使用的是5.1.1。

2. 在vue组件里导入

import Editor from '@tinymce/tinymce-vue';

如果是选项式api的话,需要做组件注册。

3. 在模板上渲染

<Editor ref="editorref" :init="{plugins: 'wordcount'}" />

4. 操作富文本实例

editorref.value.getEditor()

5、获取内容【这是最关键的一步】

editorref.value.getEditor().getContent()

完整代码【使用element-plus和ts】:

复制代码
<!-- 富文本 -->
<script lang="ts" setup>
import { ref } from "vue";
import Editor from '@tinymce/tinymce-vue'


const content = ref();

interface INews {
  title: string
}
const form = ref<INews>({
  title: ""
});
const editorRef = ref();

const addNews = () => {
  let data = {
    title: form.value.title,
    content: editorRef.value.getEditor().getContent()
  }

  console.log("data",data);
  content.value = data.content;
}


</script>

<template>
  <h1>富文本</h1>
  <el-form :model="form">
    <el-form-item label="标题">
      <el-input v-model="form.title" autocomplete="off" />
    </el-form-item>
    <editor ref="editorRef" :init="{
      height: 500,
      menubar: true,
      plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
      ],
      toolbar: 'undo redo | blocks | ' +
        'bold italic forecolor | alignleft aligncenter ' +
        'alignright alignjustify | bullist numlist outdent indent | ' +
        'removeformat | help | image | table',
      content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
    }" />

    <el-form-item>
      <el-button @click="addNews">添加</el-button>
    </el-form-item>
  </el-form>

  <hr/>
  <div v-html="content"></div>
</template>

<style lang="scss" scoped></style>
相关推荐
To_OC4 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC4 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
天渺工作室5 小时前
实现一个adblock/adblock plus等浏览器广告拦截器检测插件
前端·javascript
阳光是sunny5 小时前
Vue 项目怎么做用户行为全链路监控?轻量插件方案详解
前端·面试·架构
ZhengEnCi6 小时前
Q04-Vite禁用CSS代码分割-解决生产环境样式加载顺序混乱问题
前端·vue.js·vite
九酒6 小时前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
Jackson__7 小时前
做了一段时间的AI coding后,我终于搞清了 CLI 和 MCP 的区别
前端·agent·ai编程
IT_陈寒9 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户479492835691510 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔11 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js