vue-simplemde implements image drag and paste function (code attached)
This time I will bring you vue-simplemde to implement the image drag-and-drop function (with code). What are the precautions for vue-simplemde to implement the image drag-and-paste function. The following is a practical case. One Get up and take a look.
The project uses the vue framework and needs a markdown editing box. I searched for it on npm and found that simplemde is quite good. Since I am lazy, I searched again on npm and found it. vue-simplemde
This package, then start using it.
But thisvue-simplemde
does not support drag-and-drop upload and paste upload of images. It cannot be said that it is because of vue-simplemde, because vue-simplemde only encapsulates simplemde into a Vue plugin. So in the end, it is because simplemde does not provide relevant functions, but for the sake of user experience, this function is necessary unless the markdown editor is not used. Instead, use a rich text editor. In that case, a lot of code in the project will have to be changed. So I checked articles online and some codes on github. The following will be analyzed
Drag and drop
The core of the drag and drop API is the drop event, which is when we drag a file from the desktop to The name of the event that is triggered when the browser is released.
We all know that if you drag a picture into the browser, the picture will be opened directly. This is because the browser defaults to opening the file when you drag the file into the browser. Therefore, We need to prevent native operations.
Let’s write a piece of code now to block the default event
window.addEventListener("drop", e => { e = e || event if (e.target.className === 'CodeMirror-scroll') { // 如果进入到编辑器的话,将阻止默认事件 e.preventDefault() } }, false)
CodeMirror-scroll This Class is the Class name of the simplemde edit box.
Now we drag the file into this edit box and then release it, nothing will happen. If it is outside the edit box, the default event will still be triggered.
The following is to get the simplemde method and give it the drop Event handling method.
// 假设页面一共有三个编辑窗口,所以需要循环监听事件 [ this.$refs.simplemde1, this.$refs.simplemde2, this.$refs.simplemde3 ].map(({simplemde}) => { simplemde.codemirror.on('drop', (editor, e) => { if (!(e.dataTransfer && e.dataTransfer.files)) { // 弹窗说明,此浏览器不支持此操作 return } let dataList = e.dataTransfer.files let imageFiles = [] // 要上传的文件实例数组 // 循环,是因为可能会同时拖动几个图片文件 for (let i = 0; i <p style="text-align: left;">At first glance, the code seems to be a bit too much. That is because of the comments. The following is the code without comments. You can have your own opinions and understanding based on the following code: </p><pre class="brush:php;toolbar:false">[ this.$refs.simplemde1, this.$refs.simplemde2, this.$refs.simplemde3 ].map(({simplemde}) => { simplemde.codemirror.on('drop', (editor, e) => { if (!(e.dataTransfer && e.dataTransfer.files)) { return } let dataList = e.dataTransfer.files let imageFiles = [] for (let i = 0; i <p style="text-align: left;"><span style="color: #ff0000"><strong>Paste</strong></span></p><p style="text-align: left;">The pasting API is the paste method, this is not like Same as above, there is no need to disable the default event for pasting, because we can see that when you copy an image and press ctrl v in the browser, nothing will change, so there is no need to disable the default event. </p><p style="text-align: left;">The following is the code:</p><pre class="brush:php;toolbar:false">simplemde.codemirror.on('paste', (editor, e) => { // 粘贴图片的触发函数 if (!(e.clipboardData && e.clipboardData.items)) { // 弹窗说明,此浏览器不支持此操作 return } try { let dataList = e.clipboardData.items if (dataList[0].kind === 'file' && dataList[0].getAsFile().type.indexOf('image') !== -1) { this.uploadImagesFile(simplemde.codemirror, [dataList[0].getAsFile()]) } } catch (e) { // 弹窗说明,只能粘贴图片 } })
The reason why the try...catch method is written here is because if you paste it, if it is a file, items will be empty, and in In the if loop below, use dataList[0].kind. That is e.clipboardData.items[0].kind. When the item is empty and you access a non-existing kind attribute, an error will be reported. So here you need to use the try...catch method to judge.
dataList[0].getAsFile().type.indexOf('image') !== -1
This sentence is a judgment. The pasted thing is confirmed to be a picture and not something else. thing.
The difference between the uploaded images in if is [dataList[0].getAsFile()], because in order to unify the format and facilitate processing by the uploadImagesFile function, I added [] to make it an array. . dataList[0].getAsFile() is to get the file instance.
Upload
Uploading is a little troublesome:
uploadImagesFile (simplemde, files) { // 把每个文件实例使用FormData进行包装一下,然后返回一个数组 let params = files.map(file => { let param = new FormData() param.append('file', file, file.name) return param }) let makeRequest = params => { return this.$http.post('/Api/upload', params) } let requests = params.map(makeRequest) this.$http.spread = callback => { return arr => { return callback.apply(null, arr) } } // 服务端返回的格式是{state: Boolean, data: String} // state为false时,data就是返回的错误信息 // state为true时,data是图片上传后url地址,这个地址是针对网站的绝对路径。如下: // /static/upload/2cfd6a50-3d30-11e8-b351-0d25ce9162a3.png Promise.all(requests) .then(this.$http.spread((...resps) => { for (let i = 0; i <p style="text-align: left;">Because I encapsulate axiox into a vue plug-in to use , this will cause this.$http to be instantiated, not itself. The solution suggested by the axios maintainer is to re-introduce the axios package and use it. But I don't think it's necessary. Internally axios.all is Promise.all . The implementation code of axios.spread is relatively small, so just take it and reassign it to axios. </p><p style="text-align: left;">So the code above is </p><pre class="brush:php;toolbar:false">Promise.all(requests) .then(this.$http.spread((...resps) => { // code })
Translate this code and it will be
axios.all(requests) .then(axios.spread((...resps) => { // code })
Regarding this issue, please read the official explanation: axios-all-is-not-a-function-inside-vue-component. You can also take a look at the code of axios: axios.js#L45-L48
I won’t delve into this issue for the time being. Let’s return to the topic just now.
I mentioned above that when state is true, data is the absolute path of the file relative to the website, such as: /static/upload/2cfd6a50-3d30-11e8-b351-0d25ce9162a3.png
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
jQuery encoding conversion base64 upload through AJAX
vue component writing specification
The above is the detailed content of vue-simplemde implements image drag and paste function (code attached). For more information, please follow other related articles on the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment
