Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that the underlying list in vuedraggable is not being properly updated when elements are moved, causing them to reset. Below is a snippet of the relevant code:

<v-expansion-panels>
  <v-expansion-panel v-for="feature in groupedFeatures" :key="feature.type">
    <v-expansion-panel-title>
      <div>{{ translateFeatureType(feature.type) }}</div>
    </v-expansion-panel-title>
    <v-expansion-panel-text>
      <draggable v-model="feature.details" group="featureGroup" item-key="model_name">
        <template #item="{element, index}">
          <div :key="element.model_name">
            <p><strong>Model:</strong> {{ element.model_name }}</p>
            <p>{{ element.value }}</p>
          </div>
        </template>
      </draggable>
    </v-expansion-panel-text>
  </v-expansion-panel>
</v-expansion-panels>

Imports used in this project:

import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
import draggable from 'vuedraggable';

const route = useRoute();
const features = ref([]);
const messages = ref([]);

The onMounted function implementation:

onMounted(async () => {
    const threadData = await fetchEmailThreads(route.params.id);
  if (threadData) {
    features.value = threadData.features;
    messages.value = threadData.messages;
  }

Function for grouping features:

const groupedFeatures = computed(() => {
  const featureMap = new Map();
  features.value.forEach(f => {
    if (!featureMap.has(f.type)) {
      featureMap.set(f.type, { type: f.type, details: [] });
    }
    featureMap.get(f.type).details.push({ model_name: f.model_name, value: f.value });
  });
  return Array.from(featureMap.values());
});

Sample data structure received from the server:

{
  "chat_id": 1,
  "features": [
    {
      "model_name": "Vicuna-13B",
      "type": "abstract_feature",
      "value": "---Feature Content---"
    },
    ...
  ],
  "inst_id": 0,
  "messages": [
    {
      "content": "Message Content...",
      ...
    }
  ],
  "subject": "Topic"
}

How can I ensure that the elements in the list are correctly updated and maintain their new positions after being dragged?

Answer №1

Your groupedFeatures is not being treated as a vue ref, but instead as a computed value. Therefore, updating it with a callback from draggable won't work.

My suggestion is to reevaluate how you're calculating groupedFeatures. I recommend performing this calculation once within the onMounted callback, where you initially set your features.

const groupedFeatures = ref([]);

onMounted(async() => {
  const threadData = await fetchEmailThreads(route.params.id);
  if (!threadData) return;

  const featureMap = new Map();
  features.value.forEach(f => {
    if (!featureMap.has(f.type)) {
      featureMap.set(f.type, {
        type: f.type,
        details: []
      });
    }
    featureMap.get(f.type).details.push({
      model_name: f.model_name,
      value: f.value
    });
  });
  groupedFeatures.value = Array.from(featureMap.values());
});

By making these adjustments, your issue should be resolved.

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 apply a texture to a triangle using three.js?

I've been able to add textures to cubes, spheres, and other primitives in a scene I created. However, when it comes to adding a texture to a simple triangle, I'm encountering difficulties. Below is my attempt at achieving this: var texture=TH ...

Why is the Material Ui code functioning flawlessly in Codepen but not in VSCODE?

In my ReactJS project, I am using Material-UI to create "Material Tabs". The code works fine in SANDBOX but not in my VS CODE. What could be the issue? I have checked that Node is installed and all dependencies versions from NPM are up to date. I also tri ...

Error: Attempts to access the 'avatar' property of a null value result in a TypeError

I've been attempting to showcase both an avatar and the user name, but I keep encountering this error. Despite trying to declare a user variable to troubleshoot, it's not resolving the issue. Error: Cannot read property 'avatar' of n ...

Paper.js: Is there a way to prevent canvas height and width from changing when the window is resized?

My canvas with paperjs is set up to resize dynamically when the window is resized. I appreciate any help in advance. HTML <canvas id="myCanvas" height="800" width="1000"></canvas> JS var Initialize = function () { var canvas = document ...

Display a specific division depending on the outcome of an Ajax request within a PHP form

My PHP form has a layout similar to this: <form> <div id="inid"> National ID: <input type="text" id="individual_nid" oninput="getIndividualName(this.value)" /> </div> <hr /> name: <div id="individua ...

Can the CSS of an iframe be modified if the iframe is located on a different domain?

Is it feasible to modify the CSS of an iframe if the iframe is not located on the same domain? If so, what are some ways to apply and alter CSS for this situation? Any assistance would be greatly appreciated. <iframe id="frame1" width="100%" height="35 ...

Ensuring continuity of session in WebRTC audio calls post page refresh

Currently, I am utilizing the Kandy WebRTC library to facilitate audio calls through WebRTC. One issue I have encountered is maintaining the session alive if a user refreshes the page, as this JavaScript library operates internally using WebSocket. For in ...

An error was encountered while attempting to proxy the request [HPM]

After cloning a GitHub repository, I ran npm i in both the root directory and client directories. I then created a development configuration file. However, when attempting to run npm run dev, nodemon consistently crashes with a warning about compiled cod ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Identify support for the :first-child pseudo-class

Is there a way to determine with JavaScript whether the browser is compatible with the CSS :first-child selector? ...

Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code. <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align ...

Encountering an Issue with Vue 3 and Vue Router 4: Uncaught TypeError - Trying to Access Undefined Properties (specifically 'push')

I'm currently working with Vue 3, Vue Router 4, and TypeScript in my project. However, I've encountered an issue while trying to utilize router.push(). Every time I attempt this, I receive a console error stating: Uncaught (in promise) TypeError: ...

Associate the URL with the object to retrieve the corresponding object

When iterating through this array, I currently loop through it in the following manner: {props.choosenMovie.characters.map((characters) => ( <p>{characters}</p> /* This displays the URL of course */ ))} The URLs contain a name object th ...

Is it possible to swap out one ID value for another using JavaScript?

I am facing two issues 1) First Issue I need to update the current id value with a new one. Whenever the a tag is clicked, an event in jQuery code should be triggered to change the id value. For example, When a button is clicked <div class="video" i ...

Looking for a comprehensive calculation that takes into account various input values?

I need to display the List Price at the bottom of the form so users are aware of the cost to list their item. Within a php file, I have defined price brackets. For example, if the listing price is £150.00, it falls between £100 and £199.99 and thus nee ...

What is preventing this PHP script from functioning properly with Google Maps?

I'm having trouble understanding why this PHP script isn't generating the specified map on the HTML page. Any suggestions? <!doctype html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-sc ...

Unable to use NodeJS await/async within an object

I'm currently developing a validation module using nodeJs and I'm facing difficulties understanding why the async/await feature is not functioning correctly in my current module. Within this module, I need to have multiple exports for validation ...

Fixing the Timeout Error in Node.js & Mongoose: A Step-by-Step Guide

After developing an API, I encountered the following issue: const express = require("express"); const router = express.Router(); const {getAttendanceSheet,getDailyAttendance} = require("../../services/attendanceService"); router.get(& ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

The challenge of handling scopes in Angular-seed

I am currently facing a challenge with creating a pre-routeProvider post. The problem I'm encountering is that $http is coming up as undefined, even though I am passing it to the function as per my understanding. I have made sure to declare angular.js ...