vue3使用富文本编辑器vueQuill

在这里插入图片描述


npm install @vueup/vue-quill@alpha --save

在main.js中引入


import { createApp } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';

const app = createApp()
app.component('QuillEditor', QuillEditor)

或者在需要的模块中引入


import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';

export default {
  components: {
    QuillEditor
  }
}

使用


<QuillEditor ref="myQuillEditor" 
	theme="snow" 
	v-model="content" 
	:options="editorOption" 
/>
<!-- 使用自定义图片上传 -->
<input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
    
<script>
import { reactive, toRefs, onMounted, ref, toRaw } from 'vue'
export default {
  setup() {
    const myQuillEditor = ref()
    const fileBtn = ref()
    const data = reactive({
      content: '',
      editorOption: {
        modules: {
          toolbar: [
          	['bold', 'italic', 'underline', 'strike'],
          	[{'size': ['small', false, 'large', 'huge']}],
          	[{'font': []}],
          	[{'align': []}],
          	[{'list': 'ordered'}, {'list': 'bullet'}],
          	[{'indent': '-1'}, {'indent': '+1'}],
          	[{'header': 1}, {'header': 2}], 
          	['image'],
          	[{'direction': 'rtl' }],    //文字编辑方向,从左到右还是从右到左
          	[{ 'color': [] }, { 'background': [] }] 
          ]
        },
        placeholder: '请输入内容...'
      }
    })
    onMounted(() => {
      let quill = toRaw(myQuillEditor.value).getQuill()
      if (myQuillEditor.value) {
        quill.getModule("toolbar").addHandler("image", imgHandler);
      } 
    })
    const imgHandler = (state) => {
      if (state) {
        fileBtn.value.click()
      }
    }
    const handleUpload = (e) => {
      const files = Array.prototype.slice.call(e.target.files);
      // console.log(files, "files")
      if (!files) {
        return
      }
      let formdata = new FormData();
      formdata.append("file", files[0]);
      uploadImg(formdata)
        .then(res => {
          if (res.data.url) {
            let quill = toRaw(myQuillEditor.value).getQuill()
            let length = quill.getSelection().index;
            // 插入图片,res为服务器返回的图片链接地址
            quill.insertEmbed(length, "image", res.data.url);
            // 调整光标到最后
            quill.setSelection(length + 1);
          }
        })
    }
    return {
      myQuillEditor,
      fileBtn,
      ...toRefs(data),
      handleUpload,
      imgHandler
    }
  }
}
</script>
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值