1

I have a vue js application which allows me to add items to an array.

After adding I'd like to add the ability against each item the ability to move the item up or down the array list.

I've tried the following but I don't think Vue.JS has the move method.

My Vue method:

changePos: function(item, type = 1) {
        this.items.move(this.items, item, type);
    },

My template calling the method:

<tbody>
    <tr v-for="(item, key) in items">
        <td>
            <button class="btn btn-sm btn-rounded" @click="changePos(item,1)">UP</button>
            <button class="btn btn-sm btn-rounded" @click="changePos(item,-1)">DOWN</button>
        </td>
        <td>@{{ item.code }}</td>
    </tr>
</tbody>

I get the following error:

this.items.move is not a function

Dev.W
  • 2,340
  • 9
  • 38
  • 77
  • you need to have a method named `move()` in your `methods: {}` – samayo Oct 20 '17 at 08:59
  • Could you refer a link so I can research how to move an item up and down in an array using vue js? – Dev.W Oct 20 '17 at 09:00
  • 1
    You can find an implementation here - https://stackoverflow.com/a/5306832/1696352 – strelok2010 Oct 20 '17 at 09:47
  • I think that your problem is that you are calling `this.items.move`, but the function move(), is referenced in your Vue instance, you should call: `this.move(this.items...)` – JP. Aulet Oct 20 '17 at 10:38

1 Answers1

2

option 1: move all items up/down

function up() {
    const tmp = array.shift()
    array.push(tmp)
}

function down() {
    const tmp = array.pop()
    array.unshift(tmp)
}

option 2: use Array.map()

function up(index) {
    if (index === 0) { // if its the first in the array
        array.push(array.shift()) // same as option 1
    } else {
        array = array.map((element, i) => { // iterate array and change places
            if (i === index - 1) {
                return array[index];
            } else if (i === index) {
                return array[index - 1];
            } else {
                return element;
            }
        })
    }
}

function down(index) {
    if (index === array.length-1) { // if its the last in the array
        array.unshift(array.pop()) // same as option 1
    } else {
        array = array.map((element, i) => { // iterate array and change places
            if (i === index) {
                return array[index + 1];
            } else if (i === index + 1) {
                return array[index];
            } else {
                return element;
            }
        })
    }
}
ajin
  • 1,136
  • 1
  • 11
  • 22
reinerCode
  • 335
  • 4
  • 6