List Sorting with VueJS Drag and Drop功能

I'm currently utilizing the Vue.Draggable plugin to create a draggable list feature. I have a sorted computed property being passed in this way:

data(){

  return {

   paymentMethods: [
     { name: 'stripe', Dindex: 0, state: 2 },
     { name: 'paypal', Dindex: 1 , state: 1 },
     { name: '2checkout', Dindex: 2, state: 4 },
     { name: 'cod', Dindex: 3, state: 3 }
   ],
  }
},

computed: {

  payments() {
    return _.sortBy(this.paymentMethods, 'state');
  },
}

Here is the Drag and Drop List setup:

<draggable :list="payments" class="payment-methods" tag="ul" @start="drag=true" @end="drag=false" @change="indexChanged">
   <li v-for="(method, index) in payments" :key="index">
        <!-- list data -->
   </li>
</draggable>

The issue arises from the fact that the draggable functionality does not work as expected due to the manual sorting through lodash's _.sortBy. My question is how can I implement sorting within a draggable list.

Answer №1

After some experimentation, I've found that even though the list is a computed value, it gets sorted again when you drag it. To avoid this unnecessary sorting, my suggestion is to sort the list only once when it is mounted:

data() {
  return {
    payments: [],
    paymentMethods: [
        { name: 'stripe', Dindex: 0, state: 2 },
        { name: 'paypal', Dindex: 1 , state: 1 },
        { name: '2checkout', Dindex: 2, state: 4 },
        { name: 'cod', Dindex: 3, state: 3 }
    ],
  }
}
mounted() {
    payments = _.sortBy(this.paymentMethods, 'state');
}

Answer №2

While this solution may seem outdated, my attempts to search for an alternative through Google yielded no results. After a brief moment of contemplation, I devised the following:

// Custom Drag and Drop Component

<draggable
    class="drag-wrapper selected-cols"
    v-bind="dragOptions"
    ...other props
    @change="colChange"
>
    <div v-for="(col, i) in availableColumns" :key="col.name + '-' + i">
        <div class="drag-area">
            {{ col.label }}
        </div>
    </div>
</draggable>


// Script Section

methods: {
    colChange(e) {
        this.availableColumns.sort((a, b) =>
           a.label.localeCompare(b.label));
        },
    },

Instead of relying on a computed property for sorting, I opted to perform the sorting within the @change event listener as it is triggered post-vuedraggable reordering.

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

Create a variety of elements in real-time

My goal is to utilize JavaScript in order to generate a specific number of input boxes based on the user's input. However, I encountered an issue where using a for loop only creates one input box and then appends this same input box multiple times. f ...

Tips on adjusting a position that shifts with changes in window size

Working on a website for my grandpa, I'm planning to include a small biker character that runs across the screen. When hovered over, he stops and advises "wear a helmet." The animation works well, but there's an issue with the positioning when th ...

Is there a way to alter the color of a button once it has been clicked?

For a school project, I am working on coding a website to earn extra credit. My goal is to create a fancy design that stands out. One of the main things I am trying to achieve is having a button change color when it is clicked, similar to how it highlight ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Navigating through the realm of Android development entails understanding how to manage a multi-object function in JavaScript when using

In order to load an HTML page using the webview component and handle its functions, I am faced with a challenge. The HTML page contains a multi-object named (webkit.messageHandlers.adClicked). How can I utilize the webView.addJavascriptInterface() functi ...

Is there a way to dynamically add <td> based on the quantity of values in a JSON object?

I have developed a program that retrieves values from JSON and I aim to display these values in a table. Currently, only the last array value is being displayed in the table even though all values are available in the console. The objective now is to dynam ...

Evaluating text presence with Nightwatch and Selenium by checking for single quotes in an element

I need to verify if an element includes text with an apostrophe. I attempted: 'PROGRAMMA\'S' or "PROGRAMMA'S", such as .assert.containsText('element', 'PROGRAMMA\'S') However, neither method seems t ...

Redux export does not complete correctly unless brackets are used

I'm trying to understand why the main JS file is having trouble importing todo from './actions' without brackets, while there are no issues with importing todos from './reducers'. Main js-file: import { createStore } from 'r ...

Show HTML content from different domains within a navigation tab's content area

I am in need of showing content from a different domain on my webpage within a navigation tab. I have followed the example given in the link below: Loading cross domain endpoint with jQuery AJAX This is how my HTML code looks like: <section class=" ...

Enhance global variable by appending a line from a local function in Javascript

In my js files, I have some global functions that are used in all modules of the application. Currently, I am working on a module that requires modifying one of these global functions to run a local script every time it is called. The issue is that the g ...

Having trouble loading a React component

I've been working on breaking down modules from a monolithic React project to store them separately in my npm registry. However, I'm encountering issues with exporting and importing them correctly. Previously, I was using the following code: con ...

Utilize a store from outside a VueJS component

I am trying to set up my OpenID Connect authentication configuration using a file export const authMgr = new Oidc.UserManager({ userStore: new Oidc.WebStorageStateStore(), authority: **appsetting.oidc** }) In order to access the value of appsettting, ...

To link circles vertically with a line and fill them with color when clicked, follow these steps:

I am looking to create a design similar to the image below using unordered list items. When a user clicks on a list item, I want the circle to fill with color. I have structured it by creating a div with nested list items and span elements. If a user click ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

What is the best way to eliminate "?" from the URL while transferring data through the link component in next.js?

One method I am utilizing to pass data through link components looks like this: <div> {data.map((myData) => ( <h2> <Link href={{ pathname: `/${myData.title}`, query: { ...

Do not fetch data again after a re-render

My code is facing an issue where every time I click toggle, the Child component re-renders and triggers another API request. My goal is to fetch the data once and then keep using it even after subsequent re-renders. Check out the CodeSandbox here! functio ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Identifying the FireOS version using JavaScript

Can JavaScript be used to determine the version of FireOS that a Kindle device is running when accessing your website? ...

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...