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:
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.
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!