自定义组件 使用v-model

最近在使用vue-quill-editor富文本组件 发现默认图片都是转为base64然后写在img中,这样做会导致富文本内容体积非常庞大,然后看到某篇博客将图片上传到自己的服务器上.配置代码如下:

/*富文本编辑图片上传配置*/
const uploadConfig = {
  action:  process.env.VUE_APP_BASE_API+'file/upload',  // 必填参数 图片上传地址
  methods: 'POST',  // 必填参数 图片上传方式
  token: '',  // 可选参数 如果需要token验证,假设你的token有存放在sessionStorage
  name: 'static/file',  // 必填参数 文件的参数名
  size: 5*1024,  // 可选参数   图片大小,单位为Kb, 1M = 1024Kb
  accept: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon'  // 可选 可上传的图片格式
};

// toolbar工具栏的工具选项(默认展示全部)
const toolOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{'header': 1}, {'header': 2}],
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],
  [{'indent': '-1'}, {'indent': '+1'}],
  [{'direction': 'rtl'}],
  [{'size': ['small', false, 'large', 'huge']}],
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  [{'color': []}, {'background': []}],
  [{'font': []}],
  [{'align': []}],
  ['clean'],
  ['link', 'image', 'video']
];
const handlers = {
  image: function image() {
    var self = this;

    var fileInput = this.container.querySelector('input.ql-image[type=file]');
    if (fileInput === null) {
      fileInput = document.createElement('input');
      fileInput.setAttribute('type', 'file');
      // 设置图片参数名
      if (uploadConfig.name) {
        fileInput.setAttribute('name', uploadConfig.name);
      }
      // 可设置上传图片的格式
      fileInput.setAttribute('accept', uploadConfig.accept);
      fileInput.classList.add('ql-image');
      // 监听选择文件
      fileInput.addEventListener('change', function () {
        // 创建formData
        var formData = new FormData();
        formData.append(uploadConfig.name, fileInput.files[0]);
        formData.append('object','product');
        // 如果需要token且存在token
        if (uploadConfig.token) {
          formData.append('token', uploadConfig.token)
        }
        // 图片上传
        var xhr = new XMLHttpRequest();
        xhr.open(uploadConfig.methods, uploadConfig.action, true);
        // 上传数据成功,会触发
        xhr.onload = function (e) {
          if (xhr.status === 200) {
            var res =JSON.parse(xhr.responseText);
            console.log(res.data,'xhr')
            let length = self.quill.getSelection(true).index;
            //这里很重要,你图片上传成功后,img的src需要在这里添加,res.path就是你服务器返回的图片链接。
            self.quill.insertEmbed(length, 'image', res.data);
            self.quill.setSelection(length + 1)
          }
          fileInput.value = ''
        };
        // 开始上传数据
        xhr.upload.onloadstart = function (e) {
          fileInput.value = ''
        };
        // 当发生网络异常的时候会触发,如果上传数据的过程还未结束
        xhr.upload.onerror = function (e) {
        };
        // 上传数据完成(成功或者失败)时会触发
        xhr.upload.onloadend = function (e) {
          console.log('上传结束')
        };
        xhr.send(formData)
      });
      this.container.appendChild(fileInput);
    }
    fileInput.click();
  }
};

export default {
  placeholder: '',
  theme: 'snow',  // 主题
  modules: {
    toolbar: {
      container: toolOptions,  // 工具栏选项
      handlers: handlers  // 事件重写
    }
  }
};

页面代码如下:

<template>
  <div id="Test">
    <quill-editor ref="myTextEditor"
                  v-model="content" :options="quillOption">
    </quill-editor>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import quillConfig from './quill-config.js'

export default {
  name:'index1',
  components: {
    quillEditor
  },
  data () {
    return {
      content: '<h2>hello quill-editor</h2>',
      quillOption: quillConfig,
    }
  }
}
</script>

<style>

</style>

如果只是用一次或几次,这样写还可以.但是如果在多个页面频繁使用的话就很不方便了,所以封装了一个editor组件

<template>
  <div id="Test">
    <quill-editor ref="myTextEditor"
                  v-model="value" :options="quillOption">
    </quill-editor>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import quillConfig from './quill-config.js'

export default {
  name:'index1',
  components: {
    quillEditor
  },
  props:{
    value:{
      type:String,
      default: "",
    }
  },
  data () {
    return {
      content: '',
      quillOption: quillConfig,
    }
  }
}
</script>

<style>

</style>

可是发现使用组件的时候v-model没有生效,于是看了知乎某大佬的文章https://zhuanlan.zhihu.com/p/102706931,重新写了一下组件

<template>
  <div id="Test">
    <quill-editor ref="myTextEditor"
                  v-model="content" :options="quillOption">
    </quill-editor>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import quillConfig from './quill-config.js'

export default {
  name:'index1',
  components: {
    quillEditor
  },
  props:{
    value:{
      type:String,
      default: "",
    }
  },
  model: {
    prop: 'value',//指向props的参数名
    event: 'change'//事件名称
  },
  data () {
    return {
      content: '',
      quillOption: quillConfig,
    }
  },
  watch: {
    //监听值变化,再赋值给modelVal
    content(value) {
      this.$emit('change', value);
    }
  }
}
</script>

<style>

</style>

至此使用组件时就可以愉快的使用v-model了

 

<editor v-model="content"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值