search
HomeWeb Front-endJS TutorialHow to use Sortable in Vue

This time I will show you how to use Sortable in Vue, and what are the precautions for using Sortable in Vue. The following is a practical case, let's take a look.

I previously developed a backend management system, which used the component library Vue and Element-UI. I encountered a very interesting problem and would like to share it with you.

The scene is like this. On a list display page, I used the table component of Element-UI. The new requirement is to support drag-and-drop sorting based on the original table. However, the original component itself does not support drag-and-drop sorting, and since it is directly introduced from Element-UI, it is inconvenient to modify its source code, so the only feasible method is to directly operate the DOM.

The specific method is to perform real DOM operations on this.$el in the mounted life cycle function, listen to a series of drag events, move the DOM in the event callback, and update the data.

There are quite a lot of HTML5 Drag events, which are similar to Touch events. You can also implement them manually. However, I am lazy here and directly use an open source Sortable library and directly pass in this.$el. Listen to the encapsulated callback, and according to Vue's development model, update the actual Data data in the callback of the mobile DOM to maintain consistency between the data and the DOM.

If you think it’s over here, you are totally wrong. Sooner or later, you will have to pay back the laziness you have stolen. . . I thought this solution was very good, but as soon as I wanted to debug it, a strange phenomenon occurred: after A and B were dragged and swapped, B and A were magically swapped back again! How is this going? It seems that there is no problem with our operation. After the real DOM is moved, we also move the corresponding data. The order of the data array and the order of the rendered DOM should be consistent.

where is the problem? Let's recall the implementation principle of Vue. Before Vue2.0, two-way binding was achieved through defineProperty dependency injection and tracking. For the v-for array instruction, if a unique Key is specified, the difference of elements in the array will be calculated through an efficient Diff algorithm, and minimal movement or deletion operations will be performed. After the introduction of Virtual Dom after Vue2.0, the Dom Diff algorithm of the Children element is actually similar to the former. The only difference is that before 2.0, Diff directly targeted the array object of the v-for instruction, while after 2.0, it targeted Virtual Dom. The DOM Diff algorithm will not be described in detail here. The virtual-dom diff algorithm is explained more clearly here

Assume that our list element array is

['A','B', 'C','D']

The rendered DOM node is

[$A,$B,$C,$D]

Then the corresponding structure of Virtual Dom is

[{elm:$A,data:'A'},
{elm:$B, data:'B'},
{elm:$C,data:'C'},
{elm:$D,data:'D'}]

Assume that after drag and drop sorting, the real DOM becomes

[$B,$A,$C,$D]

At this time we only The real DOM has been manipulated and its position has been adapted, but the structure of the Virtual Dom has not changed. It is still

[{elm:$A,data:'A'},
{elm :$B,data:'B'},
{elm:$C,data:'C'},
{elm:$D,data:'D'}]

At this time, we also sort the list elements according to the real DOM and become

['B','A','C','D']

At this time, according to the Diff algorithm, the calculated Patch is. The first two items of VNode are nodes of the same type, so they are updated directly, that is, the $A node is updated to $B, and the $B node is updated to $ A, the real DOM has changed back to

[$A,$B,$C,$D]

, so after dragging and dropping, For issues updated once by the Patch algorithm, the operation path can be simply understood as

Drag and move the real DOM -> Manipulate the data array -> The Patch algorithm then updates the real DOM

Root cause

The root cause is the inconsistency between Virtual DOM and real DOM.

So before Vue2.0, because Virtual DOM was not introduced, this problem did not exist.

When using the Vue framework, try to avoid directly manipulating the DOM

Solution

1. Uniquely mark each VNode by setting the key. This is also the way Vue recommends using the v-for instruction. Because the sameVnode method will be called when judging whether two VNodes are of the same type, the priority is to judge whether the key is the same

function sameVnode (a, b) {
 return (
  a.key === b.key &&
  a.tag === b.tag &&
  a.isComment === b.isComment &&
  isDef(a.data) === isDef(b.data) &&
  sameInputType(a, b)
 )
}

2. Because the fundamental reason is that the real DOM and VNode are inconsistent, you can move the real DOM by dragging Operation restoration, that is, in the callback function, restore [$B,$A,$C,$D] to [$A,$B,$C,$D], and return the DOM operation to Vue

Drag and move the real DOM ->Restore the move operation-> Manipulate the data array-> Patch algorithm and then update the real DOM

The code is as follows

var app = new Vue({
    el: '#app', 
    mounted:function(){
      var $ul = this.$el.querySelector('#ul')
      var that = this
      new Sortable($ul, {
        onUpdate:function(event){
          var newIndex = event.newIndex,
            oldIndex = event.oldIndex
            $li = $ul.children[newIndex],
            $oldLi = $ul.children[oldIndex]
          // 先删除移动的节点
          $ul.removeChild($li)  
          // 再插入移动的节点到原有节点,还原了移动的操作
          if(newIndex > oldIndex) {
            $ul.insertBefore($li,$oldLi)
          } else {
            $ul.insertBefore($li,$oldLi.nextSibling)
          }
          // 更新items数组
          var item = that.items.splice(oldIndex,1)
          that.items.splice(newIndex,0,item[0])
          // 下一个tick就会走patch更新
        }
      })
    },
    data:function() {
      return {
        message: 'Hello Vue!',
        items:[{
          key:'1',
          name:'1'
        },{
          key:'2',
          name:'2'
        },{
          key:'3',
          name:'3'
        },{
          key:'4',
          name:'4'
        }]
      }
    },
    watch:{
      items:function(){
        console.log(this.items.map(item => item.name))
      }
    }
  })

3 .Violent solution! Without patch update, directly re-render through v-if settings. Of course, it is not recommended to do this, but I just provide this idea~

    mounted:function(){
      var $ul = this.$el.querySelector('#ul')
      var that = this
      var updateFunc = function(event){
        var newIndex = event.newIndex,
          oldIndex = event.oldIndex
        var item = that.items.splice(oldIndex,1)
        that.items.splice(newIndex,0,item[0])

        // 暴力重新渲染!
        that.reRender = false
        // 借助nextTick和v-if重新渲染
        that.$nextTick(function(){
          that.reRender = true
          that.$nextTick(function(){
            // 重新渲染之后,重新进行Sortable绑定
            new Sortable(that.$el.querySelector('#ul'), {
              onUpdate:updateFunc
            })
          })
        })
      }
      new Sortable($ul, {
        onUpdate:updateFunc
      })
    },

So, when we usually use the framework, we must also understand the implementation principle of the framework, otherwise we will not know how to deal with some difficult situations. ~

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:

How to operate nodejs to render page resources through response writeback

How to operate nodejs to use websocket

The above is the detailed content of How to use Sortable in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools