Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js add dynamic fields in list with remove and sort not working

I am using Vue js 1.0.25.

I want to create a list using dynamic textboxes. The basic idea is on clicking Add Answer button, it should create a dynamic text-box along with its index number like Ans 1 and with a Remove button.

The user can add maximum 5 answers. And also user can re-order the answers using Answer's label as a handler. I am using jQuery Sortable as Vue directive for sorting the answers.

It seems working fine, here I have created a JSFiddle for it: https://jsfiddle.net/devendragohil/6stotpaq/23/

But the problem starts when removing an answer after reordering it. Suppose, add any five answers and then reorder them randomly and after that try to remove them one by one, it will behave strange.

How can I fix it?

like image 557
Dev Avatar asked Jan 11 '17 07:01

Dev


2 Answers

I don't know where you issue is, but I think that it is related with jQuery Sortable I replicate your example using vue-sortable an it works pretty well.

Docs are easy, in short you only need to add v-sortable to your list container, and anything else should workd as you have it.

EDIT

As @g.annunziata mention it on his comment, previous example doesn't work if order and then add a new item.

To solve that we need to update data array as well, add this options on the directive v-sortable="{onUpdate: onUpdate }" and add that method on vm

onUpdate: function (event) {
   var movingElement = this.answers.splice(event.oldIndex, 1)[0];
   this.answers.splice(event.newIndex, 0, movingElement);
}

While I was trying to fix that I get another issue, if I move one element to last position and then add a new item I get this ugly error

Cannot read property 'parentNode' of null

I didn't dig into the real cause of this, but as workaround just add an invisible div after element list, something like this.

<div class="list-group" v-sortable="{ handle:'.handle', onUpdate: onUpdate }">
  <div class="list-group-item" v-for="answer in answers">
    ...
  </div>
  <div style="display:none"></div>
</div>

Example has been fixed, please see it at http://jsbin.com/qinofow/edit?html,js,output

like image 145
AldoRomo88 Avatar answered Nov 19 '22 14:11

AldoRomo88


The problem is the way you're trying to remove the element, this line here:

self.answerList.$remove(answer);

This seemed like a good place to simply remove the chosen item from the array using its index and vuejs allows for us to get it when iterating easily.

Take a look at the working fiddle here: https://jsfiddle.net/therealchiko/u9mjt5hd/2/ , I changed the function that removes the box and updated the parameters of the for loop.

like image 34
Chiko Avatar answered Nov 19 '22 12:11

Chiko