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

4
  • you need to have a method named move() in your methods: {} Commented Oct 20, 2017 at 8:59
  • Could you refer a link so I can research how to move an item up and down in an array using vue js? Commented Oct 20, 2017 at 9:00
  • 1
    You can find an implementation here - stackoverflow.com/a/5306832/1696352 Commented Oct 20, 2017 at 9: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...) Commented Oct 20, 2017 at 10:38

1 Answer 1

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;
            }
        })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.