


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 < dataList.length; i++) { // 如果不是图片,则弹窗警告 仅支持拖拽图片文件 if (dataList[i].type.indexOf('image') === -1) { // 下面的continue,作用是,如果用户同时拖动2个图片和一个文档,那么文档不给于上传,图片照常上传。 continue } imageFiles.push(dataList[i]) // 先把当前的文件push进数组里,等for循环结束之后,统一上传。 } // uploadImagesFile方法是上传图片的方法 // simplemde.codemirror的作用是用于区分当前的图片上传是处于哪个编辑框 this.uploadImagesFile(simplemde.codemirror, imageFiles) // 因为已经有了下面这段代码,所以上面的屏蔽默认事件代码就不用写了 e.preventDefault() }) })
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:
[ 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 < dataList.length; i++) { if (dataList[i].type.indexOf('image') === -1) { continue } imageFiles.push(dataList[i]) } this.uploadImagesFile(simplemde.codemirror, imageFiles) e.preventDefault() }) })
Paste
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.
The following is the code:
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 < resps.length; i++) { let {state, data} = resps[i].data if (!state) { // 弹窗显示data的错误信息 continue } let url = `` // 拼接成markdown语法 let content = simplemde.getValue() simplemde.setValue(content + url + '\n') // 和编辑框之前的内容进行拼接 } })) }
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.
So the code above is
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.
