欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue-quill-editor+plupload富文本编辑器实例详解

程序员文章站 2023-11-09 13:14:46
1,先给vue项目中下载vue-quill-editor依赖npm install vue-quill-editor --save 2,下载plupload依赖npm i...

1,先给vue项目中下载vue-quill-editor依赖npm install vue-quill-editor --save

2,下载plupload依赖npm install plupload --save

3,在组件中分别引入对应的js

import { quilleditor }from 'vue-quill-editor'
import '@/assets/js/crypto1/crypto/crypto.js'
import '@/assets/js/crypto1/hmac/hmac.js'
import '@/assets/js/crypto1/sha1/sha1.js'
import base64from '@/assets/js/base64.js'
import pluploadfrom 'plupload'

4,编写plupload上传图片需要的事件以及参数

let accessid = '阿里oss申请的accessid'
let accesskey = '阿里oss申请的accesskey'
let host = '阿里oss的存储文件地址'
let bucket = 'image'
let g_dirname = ''
let g_object_name = ''
let g_object_name_type = ''
var timestamp
let now = timestamp = date.parse(new date())/ 1000
let pos = ''
let suffix = ''
var policytext = {
'expiration': '2020-01-01t12:00:00.000z',// 设置该policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
 'conditions': [
['content-length-range',0,1048576000]// 设置上传文件的大小限制
 ]
}
var policybase64 = base64.encode(json.stringify(policytext))
let message = policybase64
var bytes = crypto.hmac(crypto.sha1,message,accesskey, {asbytes: true})
var signature = crypto.util.bytestobase64(bytes)
// 选择上传名字是本地文件名字还是随机文件名字
function check_object_radio () {
g_object_name_type = 'random_name'
}
// 默认是上传到根目录
function get_dirname () {
g_dirname = 'image/'
}
// 获得随机的字符串
function random_string (len) {
len = len || 32
 var chars = 'abcdefghjkmnpqrstwxyzabcdefhijkmnprstwxyz2345678'
 var maxpos = chars.length
 var pwd = ''
 for (var i = 0;i < len;i++) {
pwd += chars.charat(math.floor(math.random()* maxpos))
}
return pwd
}
// 获取文件后缀
function get_suffix (filename) {
pos = filename.lastindexof('.')
suffix = ''
 if (pos !== -1) {
suffix = filename.substring(pos)
}
return suffix
}
// 获取文件名字
function calculate_object_name (filename) {
if (g_object_name_type === 'local_name') {
g_object_name += filename
 }else if (g_object_name_type === 'random_name') {
suffix = get_suffix(filename)
g_object_name = random_string(10)+ new date().gettime()+ suffix
  // g_object_name = filename
 }
return ''
}
function get_uploaded_object_name (filename) {
if (g_object_name_type === 'local_name') {
var tmp_name = g_object_name
  tmp_name = tmp_name.replace(filename,filename)
return tmp_name
 }else if (g_object_name_type === 'random_name') {
return g_object_name
 }
}
// 设置上传参数
function set_upload_param (up,filename,ret) {
// g_object_name = g_dirname
 if (filename !== '') {
suffix = get_suffix(filename)
calculate_object_name(filename)
}
let new_multipart_params = {
'filename': g_dirname + g_object_name,
'key': g_dirname + g_object_name,
'policy': policybase64,
'ossaccesskeyid': accessid,
'success_action_status': '200',// 让服务端返回200,不然,默认会返回204
  'signature': signature
 }
console.log(g_object_name)
up.setoption({
'url': host,
'multipart_params': new_multipart_params
 })
up.start()
}
const toolbaroptions = [
['bold','italic','underline','strike'],// toggled buttons
 ['blockquote','code-block'],
[{'header': 1}, {'header': 2}],// custom button values
 [{'list': 'ordered'}, {'list': 'bullet'}],
[{'script': 'sub'}, {'script': 'super'}],// superscript/subscript
 [{'indent': '-1'}, {'indent': '+1'}],// outdent/indent
 [{'direction': 'rtl'}],// text direction
 [{'size': ['small',false,'large','huge']}],// custom dropdown
 [{'header': [1,2,3,4,5,6,false]}],
[{'color': []}, {'background': []}],// dropdown with defaults from theme
 [{'font': []}],
[{'align': []}],
['link','image'],
['clean']// remove formatting button
]
export default {
name: 'addnotice',
components: {
quilleditor
},
data () {
return {
loading: false,
textarea_name: '',
textarea_nei: '',
content: null,
editoroption:{
placeholder: '',
theme: 'snow',// or 'bubble'
      modules: {
toolbar: {
container: toolbaroptions,// 工具栏
        handlers: {
'image': function (value) {
if (value) {
// alert(1)
           document.queryselector('#selectfiles').click()
}else {
this.quill.format('image',false);
}
}
}
}
}
}
}
},
props: {
notice_id: number,
addnotice_id: number
  },
watch: {},
methods: {
data_qing () {
this.textarea_name = ''
    this.content = ''
   },
addnoticeoff () {
this.$emit('addnoticeoff')
},
gonggao_push () {
this.loading = true
    let data = {
token: this.token(),
id: this.addnotice_id,
match_id: this.notice_id,
title: this.textarea_name,
content: this.content
    }
this.$axios.post('/match/notice/noticesave',this.$qs.stringify(data))
.then((res)=> {
this.loading = false
      console.log(res)
if (res.data.code === '200') {
this.$emit('addnoticeoff')
this.$emit('notice_ajax',0)
}
}).catch((err)=> {
this.loading = false
     console.log(err)
})
},
escape2html (str) {
var arrentities = {'lt': '<','gt': '>','nbsp': ' ','amp': '&','quot': '"'}
return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function (all,t) {
return arrentities[t]
})
},
data_zhan () {
let data = {
token: this.token(),
id: this.addnotice_id
    }
this.$axios.post('/match/notice/noticeinfo',this.$qs.stringify(data))
.then((res)=> {
let new_data = res.data.data
      if (res.data.code === '200') {
this.textarea_name = new_data.title
       this.content = this.escape2html(new_data.content)
console.log(this.escape2html(new_data.content))
}
}).catch((err)=> {
console.log(err)
})
}
},
computed: {
},
created () {
},
mounted () {
var that = this
   var uploader = new plupload.uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'selectfiles',
multi_selection: true,
// container: document.getelementbyid('container'),
    flash_swf_url: './../assets/plupload-2.1.2/js/moxie.swf',
silverlight_xap_url: './../assets/plupload-2.1.2/js/moxie.xap',
url: host,
init: {
postinit: function () {
console.log(7777)
},
queuechanged: function (up) {// 数组变化是发生
      console.log(up)
},
filefiltered: function (up,files) {
var filesize = (math.round(files.size * 100 / (1024 * 1024))/ 100).tostring()// mb
      if (filesize > 10) {
uploader.removefile(files)
}
},
// 图片成功添加到上传队列中后的事件
     filesadded: function (up,files) {
console.log(111)
plupload.each(files,function (v,i) {
})
console.log(files)
set_upload_param(uploader,'',false)
},
beforeupload: function (up,file) {
console.log(3333)
check_object_radio()
get_dirname()
set_upload_param(up,file.name,true)
},
uploadprogress: function (up,file) {
console.log(file.percent)// 进度条设置
     },
fileuploaded: function (up,file,info) {
console.log(555)
// 获取富文本组件实例
      console.log(that.$refs)
let quill = that.$refs.myquilleditor.quill
if (info.status === 200) {
console.log(get_uploaded_object_name(file.name))
let url = host+'/'+g_dirname+get_uploaded_object_name(file.name)
// 获取光标所在位置
       let length = quill.getselection().index;
// 插入图片 res.info为服务器返回的图片地址
       quill.insertembed(length,'image',url)
// 调整光标到最后
       quill.setselection(length + 1)
}else {
this.$message.error('图片插入失败')
}
},
error: function (up,err) {
// document.getelementbyid('console').appendchild(document.createtextnode("\nerror xml:" + err.response))
     }
}
})
uploader.init()
},
destroyed () {
}
}

总结

以上所述是小编给大家介绍的vue-quill-editor+plupload富文本编辑器实例详解,希望对大家有所帮助