search
HomeWeb Front-endJS TutorialDetailed explanation of steps for using Sortable in Vue

This time I will bring you a detailed explanation of the steps for using Sortable with Vue. What are the precautions for using Sortable with Vue? Here are practical cases, 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, monitor a series of events of drag, and call back in the event Move the DOM inside 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, but here I am lazy and 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 drag After dragging and sorting, the real DOM becomes

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

At this time we only operate the real DOM, adapt Its position has been changed, but the structure of 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 The list elements are also sorted 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, the $B node is updated to $A, and the real DOM changes back to

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

So there is a problem that it is updated once by the Patch algorithm after dragging. The operation path can be simply understood as

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

The root cause

The root cause is Virtual There is an inconsistency between the DOM and the 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 operating the DOM

Solution

1. Uniquely mark each VNode by setting the key. This This is also the recommended way to use the v-for directive in Vue. 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 let the DOM operation return Drag and drop the real DOM for Vue

->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, 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
      })
    },

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 vue-cli makes cross-domain requests

Angular5 steps to add style class to component tags Explain

How to implement operator overloading in JS

The above is the detailed content of Detailed explanation of steps for using 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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

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

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

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.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

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.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

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 of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

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.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

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's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor