Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs computed properties and jquery ui sortable issue

Tags:

In my project I have a component with three ul lists. Also I have some kind of data array with items, each item has some properties. My aim is to:

  1. Distribute items in basic array into three lists
  2. Make it possible to drag&drop items between lists and accordingly update items data, since each item has a property which tells us which list the item belongs

Instead of copy-pasting a lot of code, I tried to reproduce the incorrect behaviour in jsfiddle by using simple example here:

https://jsfiddle.net/89pL26d2/4/

The thing is, when you drag&drop, you got exactly 2 items dragged, instead of one.

However, when I switched from computed properties to watch, I got the desired behaviour and everything worked just fine.

I figure out which line causes the error: the line when I update item property telling me which list the item should belong to after drag is finished. But I can't figure out why it causes this

I know that it's not the best way to work with HTML directly, but I'm okay with that for now.

like image 471
Victor Avatar asked Mar 28 '17 12:03

Victor


1 Answers

Generally, whenever I see an issue in Vue, especially related to lists, where the wrong item is updated or something like that, it comes down to Vue trying to be smart but getting it wrong because it doesn't have the best information. This is almost always solved by using a key.

It is recommended to provide a key with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.

Key.

<div id="app">
  <div>
    <ul id="listA" data-list="A" class="connectedSortable">
      <li v-for="item in listAFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
    </ul>

    <ul id="listB" data-list="B" class="connectedSortable">
      <li v-for="item in listBFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
    </ul>
  </div>
</div>

Adding a key fixes your issue.

like image 193
Bert Avatar answered Sep 21 '22 09:09

Bert