The process of updating JSON data based on changes triggered by DOM events such as drag and drop

One challenge I am facing involves a Vue component used to render child components based on JSON data. The goal is to allow users to move and add components by dragging and dropping DOM elements on the page, using tools like jQuery draggable, droppable, and Sortable.

The issue arises when each 'move' action must be synced back to the JSON for Vue to re-render the components accurately to reflect the new state.

The main hurdle lies in establishing a connection between the old and new positions of the targeted DOM element within the JSON structure as they currently lack any relationship.

Here is an example JSON snippet representing a single node in the data function:

{
 tagName: 'div',
 textNode: 'This is some text.',
 props: {
   class: '.blabla-class'
 },
 children: []
}

I've contemplated two potential solutions to address this:

  1. After a user completes a drag and drop action, I extract the corresponding DOM elements from the event and recursively traverse the DOM tree to create a positional map indicating where the element was and where it should be.

    This results in an array output, such as [0, 2, 5, 6], which guides me on how to access the JSON object (e.g., JSON[0].children[2].children[5].children[6]). Though functional, this method feels somewhat arbitrary in representing the position of a DOM element, prompting me to seek a more elegant solution.

  2. An alternative approach involves assigning a unique ID to each JSON object and its associated DOM element. Upon every move action, I would search through the entire JSON tree to locate the object with the specific ID and adjust its position relative to another anchor ID (e.g., appending after another ID). While feasible, I have concerns about the performance implications of conducting a full recursive search through a large JSON tree containing over 1000 nodes. Will this process be sufficiently fast (<50 ms)?

I am eager to hear how others would tackle this particular challenge!

Answer №1

The solution to this is quite straightforward - harness the power of the built-in HTML5 drag and drop API. Simply designate an element as draggable by setting draggable="true", then utilize the @drop and @dragstart attributes just like you would with a @click handler. While I can't provide specific guidance without seeing your code structure, you can make use of the dataTransfer.setData() and dataTransfer.getData() functions associated with these events. Remember that Vue.js operates based on data flow, so it's best to limit direct manipulation of the DOM to avoid introducing hard-to-trace bugs and creating unexpected user interactions.

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

Using Spring Boot with both XML and JSON, the application exclusively returns XML responses when utilizing Jackson

Thank you in advance for offering your assistance! I am experiencing unusual behavior within a spring boot application. Allow me to elaborate: I am integrating legacy web services (custom xml messages) with modern rest-json services using spring-mvc and ...

How to update nested properties in Typescript using bracket notation

Imagine there is an interface and object with nested properties as shown below: interface Iobj { a: { a2:string }; b: string; } const obj: Iobj = { a:{ a2: "hello" } b: "world" }; Now let's say we have strings that ...

The Three.js GLSL shader encountered a compilation error

I encountered a compile error message: THREE.WebGLShader: Shader could not compile. I attempted to use shaders from shaderfrog.com, but unfortunately they did not compile correctly. To troubleshoot, I added my new vertex and fragment shaders to the DOM a ...

The variable process.env.CLIENT_ID is functioning correctly within a function, but does not work when declared as a global

Trying to implement oAuth for Google API Using .env file to hide sensitive variables with .gitignore Facing an issue when trying to define the CLIENT_ID variable globally CLIENT_ID = process.env.CLIENT_ID When I run and log the variable outside of a fun ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Generating HTML table rows dynamically in Angular based on the number of items stored in a $scope variable

In my current project, I am utilizing Angular to dynamically populate data in an HTML table. Instead of manually coding each row for display, I am in need of a solution that allows me to programmatically define each HTML row. The Angular controller snippet ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

Adding a third-party script after closing the body tag on specific pages in NextJS can be achieved by using dynamic imports and

In my NextJS application, a third-party script is currently being loaded on all pages when it's only needed on specific pages. This has led to some issues that need to be addressed. The script is added after the closing body tag using a custom _docum ...

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

Javascript does not execute properly in Google Apps Script

Encountering issues while attempting to execute the code provided in Google app script. // 1.foldername = Folder name | 3.templateId = ID of the template to use // 2.SheetId = ID of spreadsheet to use. | 4.rootFolder = ID of the root fold ...

Discovering Constraints on File Size: API Response Encoded in Base64 Visible Within 1 Megabyte, Overcoming Rendering Obstacles

Currently, I am encountering a hurdle in my Next.js application when trying to upload images larger than 1 MB. While the app works seamlessly with smaller images, it faces challenges when dealing with larger ones. Initially, there was a browser console er ...

Attempting to execute a function within a MAP operation

My attempt to integrate a function into my map is resulting in only the function running and not the rest of the code. Edit: After reflecting on the situation, it dawned on me that I need to elaborate further. The goal here is to execute this.math in orde ...

Filter out properties from Java object with Spring framework

@PostMapping("/retrieveLargeCarList") public ResponseEntity<Cars> getLargeList( @Parameter(description = "request dto for large list") @RequestBody SearchRequest searchRequest) { return ResponseEntity.ok(someService.s ...

Is there a straightforward method to retrieve all information from Vue.js?

Is there a way to extract all of this data? I've attempted using this._data.forEach but it doesn't seem to be effective. Thank you! data() { return { childData: '', credit: '', company: '', email: ...

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

Showing an image on an ajax request

I have developed a unique user search engine that not only shows the user's details but also their profile picture. index.php if (account !="") { $.ajax({ url:"profile.php", method:"POST", ...

Is it possible to include HTML in a response when verifying emails with Node JS and Angular?

Before diving in, I want to make it clear that I have experience using APIs created in NodeJS with Angular. However, I am encountering a bit of a challenge. The issue at hand involves a function that verifies the email used during registration: exports.co ...

``From transitioning from Django templating to implementing a full RESTful architecture?

Looking to convert my django/html/css website to a REST (json) structure. Previously reliant on django template rendering for frontend responses. Interested in how to manage url redirection and incorporate json data into html templates without the use of ...

A dynamic context menu using jQuery within AJAX-loaded content

After spending hours searching for a solution without success, I am turning to this forum for help (I have come across similar questions but none of them have solved my issue). The problem I am facing is with implementing a custom context menu on a page t ...