Vue3使用wangeditor+图片宽度限制

1.下载富文本插件npm install wangeditor --save
2.写公用组件Editor.vue

<!--
 * @Description: 
 * @Version: 1.0
 * @Author: zengxianghui
 * @Date: 2022-06-01 14:31:46
 * @LastEditors: sunye
 * @LastEditTime: 2022-06-22 09:42:53
-->
<template>
  <div class="home">
    <div id="richText" style="height: 400px; background-color: #fff"></div>
    <slot name="text" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from "vue"
import { uploadFile } from "/@/api/message"
import { any } from "vue-types"
import E from "wangeditor"
import { ElMessage } from "element-plus"
//父组件传入值(编辑反显使用)
const props = defineProps({
  editorValue: {
    type: String,
    default: ""
  }
})
const emit = defineEmits(["getMsg"])
const phoneEditor = ref("")

onMounted(() => {
  seteditor()
  phoneEditor.value.txt.html(props.editorValue)
})
watch(
  () => props.editorValue,
  (newValue, oldValue) => {
    // 富文本内容
    if (newValue !== phoneEditor.value.txt.html()) {
    //防止光标换行乱跳
      phoneEditor.value.txt.html(newValue)
    }
  }
)
const seteditor = () => {
  phoneEditor.value = new E("#richText")
  if (phoneEditor.value != null) {
    phoneEditor.value.destroy() //判断编辑器是否被创建,如果创建了就先销毁。
  }
  // 上传图片到服务器,base64形式
  phoneEditor.value.config.uploadImgShowBase64 = true
  // 隐藏网络图片
  phoneEditor.value.config.showLinkImg = false
  // 创建一个富文本编辑器
  phoneEditor.value.create()
  phoneEditor.value.config.uploadImgMaxSize = 10 * 1024 * 1024 //限制图片大小
  phoneEditor.value.config.onchange = html => {
  //富文本信息传给父组件
    emit("getMsg", html)
  }
  phoneEditor.value.config.customUploadImg = (files, insert) => {
    // 富文本里的上传图片
    const param = new FormData()
    param.append("photos", files[0])
    let reader = new FileReader()
    reader.readAsDataURL(files[0])
    reader.onload = function (e) {
      let img = new Image()
      img.src = e.target.result //获取编码后的值
      img.onload = function () {
        // 限制图片宽度
        if (img.width >= 800 && img.width <= 1200) {
          uploadFile("upload", param).then(res => {
            // 上传图片接口
            if (res.data) {
              console.log(res)
              insert(res.data.domainName + res.data.uris[0])
            }
          })
        } else {
          return ElMessage.error("上传图片宽度在800-1200之间")
        }
      }
    }
  }
}
</script>

<style scoped></style>

父组件使用

//import引入组件
<el-form-item label="图片上传" prop="chart">
        <UploadImg
          :imgWidth="bannerState.imgWidth"
          :imgHeight="bannerState.imgHeight"
          @getImg="getImg"
          :validateImgSize="true"
          :fullUrl="bannerState.form.chart"
        />
      </el-form-item>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值