Managing nested levels in Vue Draggable

Here is a link to the code sandbox: Nested Draggable Code Sandbox

The nesting in this code is controlled through directives, specifically using v-if:

<template>
  <draggable class="dragArea" tag="ul" :list="tasks" :group="{ name: 'g1' }">
    <li v-for="el in tasks" :key="el.name">
      <generic-item :taskItem="el"> </generic-item>
      <p>{{ el.name }}</p>
      <div v-if="el.type === 'inventoryCategory'">
        <nested-draggable :tasks="el.tasks" />
      </div>      
    </li>
  </draggable>
</template>

This structure creates recursion that stops at the category level where each section includes a category and a category includes none or more items.

The problem arises when sections can be dragged into one another. The desired behavior is for a section to only contain items. How can this conflict be resolved?

The current approach infers the type by checking a field ("type": "inventoryCategory") against possible values and rendering tags accordingly.

Answer №1

Here's what I came up with:

Check out the code here

(organization of nested elements can be found in this link)

validateMove: function (event) {
  // Ensure items stay within categories
  if (element.type === "inventoryItem") {
    if (event.to.childNodes.length > 0) {
      let categoryCount = 0;
      for (let i = 0; i < event.to.childNodes.length; ++i) {
        if (event.to.childNodes[i].getAttribute("element-type") === "inventoryCategory") {
          categoryCount++;
        }
      }
      if (categoryCount === event.to.childNodes.length) {
        return false;
      }
    } else {
      return true;
    }
  }
  // Prevent nesting of categories
  if (event.from !== event.to && element.type === "inventoryCategory") {
    return false;
  }
  return true;
},

)

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

Correct Way to Use 'useState' in Formik's 'onSubmit' Function?

I recently encountered an issue while using Formik in my Next.js application. Specifically, I am facing a problem with the submit `Button` component, which accepts a `showSpinner` prop to control its behavior. When set to true, the button is disabled and d ...

What sets apart the $ and $() functions in jQuery?

After reviewing the jQuery API, I noticed that $() represents a collection of matched elements. However, I am curious about the significance of $. An example from the imagesLoaded library is provided below. if ( $ ) { $.fn.imagesLoaded = function( opt ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

The Express server's `GET` request at the root does not seem

When I access localhost:8080/chat?k=1&d=1, the console displays "CHAT PAGE" and everything works correctly. However, when I try to visit localhost:8080, the root event does not display "INDEX PAGE" as expected. Instead, it automatically retrieves ind ...

What is the best way to trigger dependent APIs when a button is clicked in a React Query application

On button click, I need to call 2 APIs where the second query depends on the result of the first query. I want to pass data from the first query to the second query and believe using "react-query" will reduce code and provide necessary states like "isFetch ...

Error 405 (Invalid Method) in VueJs: You are not allowed to use

I have a route defined in the group with 'prefix'=>'admin' in web.php Route::post('/slideUpdate/{id}','SlideController@postSlideUpdate') In Add.vue, I am calling the update() function in methods axios.patch(`/a ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

Prevent the risk of revealing your LinkedIn API key within HTML code

For my website, I am looking to incorporate the Sign In With LinkedIn feature for user logins. The initial example snippet provided in the LinkedIn API docs is as follows: <script type="text/javascript" src="//platform.linkedin.com/in.js"> api_k ...

Get connected to your favorite music on iTunes without the hassle of opening a new window by simply clicking on the

Is there a way to call a link to iTunes (itms://...) without opening a new window? I've tried using window.open but that just opens a new window. Also, $.get('itms://...'); doesn't seem to work for me. Are there any other options avail ...

Tips on excluding certain attributes in Vue 3?

I am looking to incorporate tailwind-merge into my Vue component to avoid conflicts with tailwind classes. An issue I've encountered is that when using useAttrs and adding a parent class, the additional classes are being duplicated. The most straight ...

The conditional rendering issue in Mui DataGrid's renderCell function is causing problems

My Mui DataGrid setup is simple, but I'm encountering an issue with the renderCell function not rendering elements conditionally. The default behavior should display an EditIcon button (the pencil). When clicked, it triggers the fetchSomething functi ...

The zoom level on Google Maps adjusts based on the size of the window when it

In reference to my previous inquiry about Google maps responsive resize, I am now looking to incorporate dynamic zoom levels based on the window size. Specifically, I want the map to automatically adjust its zoom level when the browser window is resized -- ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

Guide to setting the hiddenfield value within a listview using javascript or jquery

Here is the javascript code that I am using to retrieve the value from my textbox with autocompleteextender. <script type="text/javascript"> function txt_lect_in_AutoCompleteExtender_itemSelected(sender, e) { var hdEmpId = $get('& ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Go all the way down to see the latest messages

I have developed a messaging system using Vue. The latest messages are displayed from bottom to top. I want to automatically scroll to the end of a conversation when it is clicked and all the messages have been loaded via axios. Conversation Messages Comp ...

Execute an asynchronous function in Javascript, then output the returned data to the console

Is there a way to effectively handle the data returned from an async function? example: JS FILE: async function getData(){ try { $.getJSON('./data.json', (data) => { return data; }); } catch(error ...