vue3 - vite 中使用 tiptap 富文本编辑器的方法及注意事项

在这里插入图片描述

一、安装 tiptap

使用一下命令进行安装:

npm install @tiptap/vue-3 @tiptap/pm @tiptap/starter-kit

starter-kit 里面包含了一些基础的可操作组件,如 :标题、正文、加粗、斜体、有序列表、无序列表、撤销、恢复

如果想要其他功能,如:下划线、文字对齐、图片等,需要进行另外的安装

下划线:

npm install @tiptap/extension-underline

文字对齐:

npm install @tiptap/extension-text-align

图片:

npm install @tiptap/extension-image

提示:

图片功能只是根据图片地址来展示图片,要实现点击图片按钮后上传图片然后展示图片 的功能,需要自己编写上传图片的方法,将上传图片接口返回的图片地址 赋值给 tiptap 图片组件,插入图片后展示图片。

其他更多操作功能可以查阅 tiptap 官网:tiptap编辑功能列表页

二、组件中使用 tiptap 方法

我是将富文本编辑器放在一个单独的 子组件中,父组件引用子组件,所以需要父子组件之间传参,动态绑定 富文本编辑器的内容值,本来先用 Vue3 的 <script setup lang=“ts”> 组合API 格式写,tiptap官网上没有,只有 选项API格式示例,尝试自己改了下没改出来,先暂时用一下 选项API格式实现功能,后面再用组合式API格式写写,弄出来了再更新文章~

1、组件中 引入 StarterKit、Editor及EditorContent

如下:

import StarterKit from '@tiptap/starter-kit'
import {
    Editor, EditorContent } from '@tiptap/vue-3'

2、注册 引入的 富文本编辑器组件,创建编辑器实例及监听内容变化

富文本编辑器子组件:

<script>
import {
    ref } from 'vue'
import StarterKit from '@tiptap/starter-kit'
import {
    Editor, EditorContent } from '@tiptap/vue-3'

export default {
   
  components: {
   
    EditorContent,  // 注册富文本编辑器内容展示组件
  },

  props: {
   
    show: {
     // 是否展示富文本编辑器组件(子组件)
      type: Boolean,
      default: false,
    },
    contentVal: {
     // 父组件的富文本内容值
      type: String,
      default: '',
    },
  },

  emits: ['update:contentVal', 'update:show'],  // 内容值、组件是否展示值的更新方法

  data() {
   
    return {
   
      contentValue: '',  // 子组件的富文本编辑器内容值
      editor: null,  // 富文本编辑器对象
      addBtnDisabled: false,  // 确认保存编辑内容按钮是否禁用状态
    }
  },
  methods: {
   
    closeFn() {
   
      this.$emit('update:show', false)
    },
    confirmFn() {
     // 确认更新内容
      const isEmpty = this.editor.isEmpty  // 编辑器内容是否为空,true:为空;false:不为空
      if (isEmpty) {
   
        this.$emit('update:contentVal', '')
      } else {
   
        this.$emit('update:contentVal', this.editor.getHTML())
      }

      this.$emit('update:show', false)
    },
  },

  watch: {
     // 监听编辑器内容变化
    contentValue(value) {
   
      const isSame = this.editor.getHTML() === value
      // 判断修改后的内容和之前内容是否一样,一样的话返回,不进行更新操作
      if (isSame) {
   
        return
      }
       // 内容有改变,更新编辑器内容
      this.editor.commands.setContent(value, false)
    },
  },

  mounted() {
   
    this.contentValue = this.contentVal
    // 创建编辑器实例对象
    this.editor = new Editor({
     // 创建编辑器实例对象
      extensions: [StarterKit],   // StarterKit包含一些基础组件
      content: this.contentValue,

      onUpdate: (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值