vue elemtent-ui框架集合富文本vue-quill-editor以及解决富文本的图片上传问题

cnpm install --save 下载富文本包

<template>
  <div>
    <el-dialog title="修改"
               :close-on-click-modal="false"
               :visible.sync="visible"
               width="50%"
               :show-close="true">
      <el-form :model="ruleForm"
               :rules="rules"
               ref="ruleForm"
               label-width="100px"
               class="demo-ruleForm addForm">
        <el-form-item label="跳转网址:"
                      prop="lhttp">
          <quillEditor v-model="ruleForm.lhttp"
                       ref="myQuillEditor"
                       :options="editorOption"
                       @blur="onEditorBlur($event)"
                       @focus="onEditorFocus($event)"
                       @change="onEditorChange($event)">
          </quillEditor>
        </el-form-item>
        <el-form-item label="排序:"
                      prop="content">
          <el-input v-model.number="ruleForm.lpid"
                    class="addIpt"></el-input>
        </el-form-item>
      <!--富文本上传图片的隐藏按钮-->
        <el-form v-show="false">
          <el-upload class="image_add"
                     :action="apiUrl"
                     :headers="headers"
                     :on-success="imageHandleSuccess"
                     :before-upload="beforeAvatarUpload"
                     :name="imgname"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
          </el-upload>
        </el-form>
        <el-form-item label="内容:"
                      prop="img">
          <el-upload class="upload-demo"
                     :action="apiUrl"
                     :headers="headers"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     :before-remove="beforeRemove"
                     :before-upload="beforeAvatarUpload"
                     :name="imgname"
                     :limit="1"
                     :on-exceed="excedeImage"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="状态 :"
                      prop="lstatus">
          <el-radio-group v-model="ruleForm.lstatus">
            <el-radio :label="1">正常 </el-radio>
            <el-radio :label="2">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="submitForm('ruleForm')">立即修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
//自定义的富文本上传功能数组
import { toolbarOptions } from '@/utils/common.js'
export default {
  components: {
    quillEditor
  },
  inject: ['reload'],
  data () {
    return {
      fileList: [],
      imgname: 'img',
      visible: false,
      options: [],
      ruleForm: {
        lstatus: '1',
        content: '',
        title: ''
      },
      editorOption: {
        placeholder: '',
        theme: 'snow',  // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.image_add input').click() // 调用隐藏的element 图片上传按钮
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      rules: {
        lpid: [
          { required: true, message: '请输入排序', trigger: 'blur' },
          { type: 'number', message: '请输入数字' }
        ],
        lhttp: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        lstatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        img: [
          { required: true, message: '请上传轮播图', trigger: 'change' }
        ]
      }
    }
  },
  // 计算属性
  computed: {
    img: function () {
      return this.ruleForm.img
    },
    lstatus: function () {
      return this.ruleForm.status
    },
    headers: function () {
      return { 'token': this.$cookie.get('token') }
    },
    apiUrl: function () {
      return this.$http.adornUrl('/api/AdminNews/pictureUpload')
    }
    // editor() {
    //       return this.$refs.myTextEditor.quill;
    // },
  },
  // 侦听器
  watch: {

  },

  methods: {
    init (id) {
      let that = this
      that.fnGetInfo(id)
      that.visible = true
    },
    handleRemove (file) { // 文件移除
      this.ruleForm.img = {}
    },
    handleSuccess (response, file, fileList) { // 文件上传成功
      if (!response.url) {
        this.fileList = []
        this.$message({
          type: 'error',
          message: '请重新选择上传文件'
        })
        return false
      }
      this.ruleForm.img = response.url
    },
    beforeAvatarUpload (file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        this.fileList = []
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        this.fileList = []
      }
      return isJPG && isLt2M
    },
    handlePreview (file) { // 文件上传前钩子
      console.log(file)
      this.ruleForm.img = file
    },
    beforeRemove (file) {
      return this.$confirm(`确定移除 ${file.name}?`)
    },
    excedeImage (files, fileList) {
      this.$message.error('超出数量限制,如需更改请先删除在上传!')
    },

    onEditorBlur (editor) {
      // console.log('editor blur!', editor)
    },
    onEditorFocus (editor) {
      // console.log('editor focus!', editor)
    },
    onEditorReady (editor) {
      // console.log('editor ready!', editor)
    },
    onEditorChange ({ editor, html, text }) {
      // console.log('editor change!', editor, html, text)
      this.content = html
    },
    imageHandleSuccess (response, file, fileList) { // 文件上传成功
      if (!response.url) {
        this.fileList = []
        this.$message({
          type: 'error',
          message: '请重新选择上传文件'
        })
        return false
      }
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      // 如果上传成功
      if (response.code == '1' && response.url !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', this.httpUrl + response.url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },

    // 获取数据
    fnGetInfo (id) {
      this.$http({
        url: this.$http.adornUrl('/api/AdminNews/editWheel'),
        method: 'post',
        data: this.$http.adornData({
          lid: id
        })
      }).then(({ data }) => {
        if (data.code == '1') {
          this.ruleForm = data.data
          this.fileList = [{ name: 'banner', url: this.httpUrl + data.data.pic }]
          this.ruleForm.img = data.data.pic
        } else {
          this.$message({
            type: 'error',
            message: data.msg
          })
        }
      })
    },
    // 提交操作
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.type = 'edit'
          this.$http({
            url: this.$http.adornUrl('/api/AdminNews/editWheel'),
            method: 'post',
            data: this.$http.adornData(this.ruleForm)
          }).then(({ data }) => {
            if (data.code === '1') {
              this.$message({
                type: 'success',
                message: data.msg
              })
              this.reload()
              this.visible = false
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
.addForm {
  margin: 0 auto;
  width: 60%;
  .el-select {
    width: 100%;
  }
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值