Home Web Front-end Vue.js How to use Vue and Element-UI to implement data dragging and sorting functions

How to use Vue and Element-UI to implement data dragging and sorting functions

Jul 21, 2023 pm 05:09 PM
vue element-ui Data drag and drop

How to use Vue and Element-UI to implement data dragging and sorting functions

Introduction:
With the development of web applications, data dragging and sorting functions have become necessary for many applications part. As a modern JavaScript framework, Vue.js provides convenient data binding and component-based development methods, while Element-UI, as a UI framework based on Vue.js, provides a series of excellent components and interactive effects. This article will introduce how to use Vue and Element-UI to implement data dragging and sorting functions, and give sample code.

  1. Preparation work
    Before we start, we need to prepare the relevant development environment. First, make sure you have Node.js and npm installed. Then, install Vue and Element-UI via npm.

    npm install vue
    npm install element-ui
    Copy after login

    After the installation is complete, create a new Vue project and introduce the Element-UI library.

    vue create drag-sort-demo
    cd drag-sort-demo
    npm install element-ui
    Copy after login

    Next, introduce Vue and Element-UI into Vue’s entry file main.js, and use the Vue.use() method to register Element-UI components.

    import Vue from 'vue'
    import ElementUI from 'element-ui'
    import 'element-ui/lib/theme-chalk/index.css'
    
    Vue.use(ElementUI)
    
    new Vue({
      render: h => h(App)
    }).$mount('#app')
    Copy after login

    So far, we have completed the preparation work, and next we will start to implement the data drag and sort function.

  2. Implementing data list
    First, we need to create a data list to display data items that can be dragged, dropped, and sorted. In Vue components, you can use the v-for directive to traverse the data list, and use the el-card component to display each data item.

    <template>
      <div>
     <el-card v-for="item in list" :key="item.id">
       {{ item.name }}
     </el-card>
      </div>
    </template>
    
    <script>
    export default {
      data() {
     return {
       list: [
         { id: 1, name: '数据项1' },
         { id: 2, name: '数据项2' },
         { id: 3, name: '数据项3' },
         { id: 4, name: '数据项4' },
         { id: 5, name: '数据项5' }
       ]
     }
      }
    }
    </script>
    Copy after login

    Now, we have completed the display of the data list.

  3. Add drag and drop function
    Next, we will add drag and drop function for each data item. In Element-UI, you can use the el-draggable directive to implement the drag-and-drop function. We can add the el-draggable directive to the el-card component and bind a property related to the data item.

    <template>
      <div>
     <el-card v-for="item in list" :key="item.id" v-el-draggable="item">
       {{ item.name }}
     </el-card>
      </div>
    </template>
    
    <script>
    export default {
      // ...
      directives: {
     'el-draggable': {
       bind(el, binding, vnode) {
         el.draggable = true
         el.addEventListener('dragstart', (event) => {
           event.dataTransfer.setData('text/plain', JSON.stringify(binding.value))
         })
       }
     }
      }
    }
    </script>
    Copy after login

    In the el-draggable directive, we set the draggable attribute of the element to true to enable dragging functionality. Then, in the dragstart event, we store the value of the current data item as a JSON string into the DataTransfer object.

  4. Add sorting function
    In addition to the drag and drop function, we also need to implement the sorting function after dragging the data items to the specified position. In Element-UI, you can use the el-dropzone directive to implement the sorting function. We can add the el-dropzone directive to the container where the el-card component is located and bind a property related to the data list.

    <template>
      <div v-el-dropzone="list">
     <el-card v-for="item in list" :key="item.id" v-el-draggable="item">
       {{ item.name }}
     </el-card>
      </div>
    </template>
    
    <script>
    export default {
      // ...
      directives: {
     'el-draggable': {
       // ...
       bind(el, binding, vnode) {
         // ...
         el.addEventListener('dragend', () => {
           vnode.context.$forceUpdate();
         })
       }
     },
     'el-dropzone': {
       bind(el, binding, vnode) {
         el.addEventListener('dragover', (event) => {
           event.preventDefault()
         })
         el.addEventListener('drop', (event) => {
           event.preventDefault()
           const draggedItem = JSON.parse(event.dataTransfer.getData('text/plain'))
           const newList = binding.value.slice()
           const index = newList.findIndex(item => item.id === draggedItem.id)
           newList.splice(index, 1)
           newList.splice(el.dataset.index, 0, draggedItem)
           vnode.context[binding.expression] = newList
         })
       }
     }
      }
    }
    </script>
    Copy after login

    In the el-dropzone directive, we call the preventDefault method in the dragover event to prevent the browser's default drag-and-drop behavior. Then, in the drop event, we get the dragged data item and find its position in the original data list based on its id. We then create a new copy of the data list, remove the dragged data item from it, and insert the data item at the specified location. Finally, we update the data list by modifying the corresponding data attributes in the Vue instance.

  5. Effect display

After implementing the above steps, we have completed the development of data drag and sort functions. Now we can run the project and see the effect.

npm run serve
Copy after login

Open the browser and visit http://localhost:8080 to see the data list with drag-and-drop and sorting functions.

Conclusion:
This article details how to use Vue and Element-UI to implement data dragging and sorting functions. By using the el-draggable and el-dropzone directives, we can easily add dragging and sorting functionality to the data list. I hope this article will be helpful to developers who are developing web applications so that they can implement this common function more efficiently.

Reference link:

  • Vue official documentation: https://cn.vuejs.org/
  • Element-UI official documentation: https://element. eleme.io/

The above is the detailed content of How to use Vue and Element-UI to implement data dragging and sorting functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles