Tips for effectively utilizing vue-draggable (or Sortable JS) within a v-data-table using the powerful combination of Vuetify 2 and Vue JS 2

I'm currently experimenting with integrating vue-draggable into Vuetify's v-data-table based on the instructions provided in this article : https://medium.com/vuetify/drag-n-drop-in-vuetify-part-ii-2b07b4b27684

The article mentions : "The main objective was to make the tbody of the table a draggable component, which proved challenging due to Vuetify utilizing templates for item rendering."

Subsequently, the individual discovered a solution involving Sortable JS. I attempted to implement it but encountered issues.

An error message stating: Sortable: el must be an HTMLElement, not [object Function], keeps appearing.

According to some sources, Sortable JS may not function properly with Vue JS 2...

What should I do next?

If you have a resolution, kindly share it with me :)

This is my code :

    <v-data-table
      :headers="headers"
      :items="slots"
      :items-per-page="-1"
      ref="sortableTable"
    >
      <template v-slot:item="props">
        <tr v-if="props.item.recipe" class="sortableRow">
          <td style="text-align: center">{{props.item.slot}}</td>
          <td style="text-align: center" v-if="props.item.recipe.preferences">
            <v-chip
            v-for="pref in props.item.recipe.preferences"
            :key="pref"
            small
          >
            {{ pref }}
          </v-chip>
          </td>
          <td style="text-align: center">{{props.item.recipe.protein}}</td>
          <td style="text-align: center">{{props.item.recipe.protein_cut}}</td>
          <td style="text-align: center">{{props.item.recipe.carb}}</td>
          <td style="text-align: center" v-if="props.item.recipe.tags">
            <v-chip
              v-if="props.item.recipe.tags.indexOf('c3_appropriate') !== -1"
              small
              color="success"
              text-color="white"
            >
              C3
            </v-chip>
          </td>
          <td style="text-align: center">{{props.item.recipe.ready_in}}</td>
          <td style="text-align: center">
            <v-chip
              small
              :color="props.item.recipe.new_repeat === 'repeat' ? 'error' : 'success'"
            >
              {{ props.item.recipe.new_repeat }}
            </v-chip>
          </td>
          <td style="text-align: center">
            {{ props.item.recipe.title + ' ' }}
            <span
              v-if="props.item.recipe.subtitle"
              style="font-size: 11px"
            >
                <br>
                {{ props.item.recipe.subtitle }}
              </span>
          </td>
        </tr>
        <tr v-else>
          <td style="text-align: center">{{props.item.slot}}</td>
        </tr>

      </template>
    </v-data-table>


mounted() {

        let table = document.querySelector("table tbody");
        console.log(table)
        const _self = this;
        Sortable.create(table, {
            draggable: '.sortableRow',
            handle: ".handle",
            onEnd({newIndex, oldIndex}) {
                const rowSelected = _self.slots.splice(oldIndex,1)[0];
                _self.slots.splice(newIndex, 0, rowSelected);
            }
        });
    }

Answer №1

Implementing SortableJS with Nuxt has been a challenge for me. After exploring various solutions, I settled on creating a custom directive using Vue.directive:

import Vue from 'vue'
import {Sortable} from 'sortablejs';
Vue.directive("sortableDataTable", {
  bind(el, binding, vnode) {
    const options = {
      animation: 150,
      onUpdate(event) {
        vnode.child.$emit('sorted', event)
      }
    }
    Sortable.create(el.getElementsByTagName('tbody')[0], options)
  }
})

With this setup, I can now apply the v-sortable-data-table directive within a v-data-table:

  <v-data-table
    v-sortable-data-table
    :items="items"
    :headers="headers"
    item-key="id"
  >
  </v-data-table>

It's worth noting that while the directive is registered as sortableDataTable, it should be used as v-sortable-data-table to adhere to kebab-case naming conventions and include the 'v-' prefix.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to merge javascript files and have them load after the page has already loaded on an asp.net site?

I recently came across a helpful SE Post that discussed combining external javascript files for better optimization, which is something I'm interested in. Following recommendations, I have converted internal javascripts into an external .js file and s ...

The standalone package for webpack's CLI tool has been introduced as webpack-cli

Currently venturing into the world of React.js, I decided to follow the tutorials provided on tutorialspoint. However, during the implementation phase, I encountered an error message in the console upon executing the 'npm start' command: C:&bsol ...

Developing a personalized logging service in NestJs: capturing logs without directly outputting them

I am currently working on developing a NestJs service that will enhance a Logger. However, I am facing issues with achieving the desired output (e.g., super.warn(); see below for more details). I have followed a tutorial from the nestjs site, but unfortuna ...

Issue with Laravel Sanctum and Vue CLI not properly storing cookiesalternatively:Cookies

Currently, I have Laravel 8 installed on a remote server, and my aim is to authenticate from the Vue CLI running on localhost using Sanctum. The issue arises when I submit the login form as it confirms authentication but fails to set the cookies in the bro ...

Analyzing data from a JSON API response for calculations

Can someone help me figure out how to add a percentage or number to each value in the total field of my code? I've tried multiple approaches but nothing seems to work. <?php $json=file_get_contents("http://www.upliftinghumanity.net/edd-api/sales/ ...

Questions about clarifying JS promises and async-await functions

After doing some reading on promises in JavaScript, I have come across conflicting information which has left me with a few basic questions. I have two specific questions that need clarification: Is it necessary for every function in JavaScript to be ca ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

Choose a specific <div> element by its unique ID and trigger a click event on it as soon as the page loads

There is a div element on my webpage tagged with the ID of #activateeditbutton. I am hoping to have this specific div trigger a click event upon the page's initial loading. In an attempt to achieve this functionality via jQuery, I have written the fo ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

Updating input value in React on change event

This is the code for my SearchForm.js, where the function handleKeywordsChange is responsible for managing changes in the input field for keywords. import React from 'react'; import ReactDOM from 'react-dom'; class SearchForm extends ...

Clever ways to refresh the current page before navigating to a new link using ajax and jQuery

Here's a different perspective <a href="{{$cart_items->contains('id',$productItem->id) ? route('IndexCart'): route('AddToCart')}}" class="item_add" id="{{$productItem->id}}"><p class="number item_price ...

Alter the class following modifications to the list

https://i.stack.imgur.com/QZob0.pngIn my dual list, the data is displayed in a ul li format fetched from a JSON file. Users can move items between the two lists. However, I am facing an issue where I want to apply a property that only displays content with ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...

Organizing HTML elements based on their class names, especially when an element has multiple classes assigned

Hey there, I've been working on an artist page that showcases multiple artists, each with a portfolio image and some detailed information. My goal is to have buttons at the top of the page that, upon clicking, will sort the artists displayed. To achi ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Set up counters for a variety of Owl Carousel sliders

I am looking to set up multiple owl carousel sliders, where each slider has a counter to track its position. I want the counters to update independently, but I'm running into issues with them not working correctly. Each slider should display a counte ...

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

Steps to eliminate a choice from the MUI Datagrid Column Show/Hide feature

I am attempting to customize which columns are displayed on the <GridToolbarColumnsButton/> component within the MUI Datagrid toolbar (refer to the image below) https://i.stack.imgur.com/joZUg.jpg Potential solution: I have been exploring the AP ...

Using CSS in combination with AngularJS, you can create a dynamic growth effect for a div element that initially

I am currently using AngularJS to dynamically add divs to a section. My goal is to have each div start with a static width and then grow dynamically as I continue to add more divs. How can I achieve this? The following code is not producing the desired re ...