Reorganize items in an array using Vue JS for upward and downward movements

In my Vue JS application, I have a feature that allows users to add items to an array.

After adding an item, I want to give users the ability to move the item up or down the array list.

I attempted to achieve this functionality with the following Vue method:

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

However, when calling this method in my template, I encountered an error:

this.items.move is not a function

This is how I called the method in my template:

<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>

Answer №1

Method 1: Adjusting item positions

function moveUp() {
    const temp = array.shift();
    array.push(temp);
}

function moveDown() {
    const temp = array.pop();
    array.unshift(temp);
}

Method 2: Leveraging Array.map()

function moveUp(index) {
    if (index === 0) {
        array.push(array.shift());
    } else {
        array = array.map((element, i) => {
            if (i === index - 1) {
                return array[index];
            } else if (i === index) {
                return array[index - 1];
            } else {
                return element;
            }
        });
    }
}

function moveDown(index) {
    if (index === array.length-1) {
        array.unshift(array.pop());
    } else {
        array = array.map((element, i) => {
            if (i === index) {
                return array[index + 1];
            } else if (i === index + 1) {
                return array[index];
            } else {
                return element;
            }
        });
    }
}

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

Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or ...

Choose a specific <div> element from an external page using Ajax/PHP

I'm encountering a small issue. I am currently utilizing Ajax to dynamically load content from another page into a <div> element after detecting a change in a <select>. However, my specific requirement is to only load a particular <div& ...

Adjusting the color of an element in ReactJS as the user scrolls and hits a specific position

Is there a way to dynamically change the color of my header based on the background color as I scroll through different sections of my webpage? I have a fixed header and multiple sections with varying background colors. I want the header's text color ...

Retrieve an array field across various documents and combine the elements to form a single object

Consider a scenario where there is a users collection. Each user document includes an array of posts called posts. The goal is to query this collection as follows: Retrieve 2 posts, starting at index Nstart and ending at index Nend, from each user in the ...

Dynamic content for tooltips in Angular

Currently, I am facing a challenge where I need to dynamically populate content in a tooltip by executing a function with a parameter. This parameter holds the crucial information required to update the tooltip content. The complexity arises from the fact ...

What is the best way to send a prop to my home route following a redirect?

I am working with react-router-dom and I want to pass :id to my first route (/) when redirecting. This is important so that I can access :id in my Interface component and maintain consistent URL structure for my single-page application. Is it feasible to a ...

What are some ways to transfer information seamlessly between two PHP files without the need for a page refresh?

On my webpage, I have implemented two iframes. The first iframe contains a button that, when clicked, should reload the second iframe with specific data, without reloading the first iframe. I am looking for a way to achieve this. Can anyone help? <?p ...

Issue with submitting form data using ajax

Apologies for the question, but I am struggling to make progress with this. Here is the form that I am working on within a PHP loop: <form name="primaryTagForm'.$post->ID.'" id="primaryTagForm'.$post->ID.'" method="POST" encty ...

Pulling XML data with React-Native

Just starting out with React-Native and trying to build some basic apps. I am struggling with fetching XML data, as JSON seems much more straightforward. I have attempted to convert the XML data to JSON using a few different scripts, including this, but h ...

Creating a two-dimensional array in C++ using strings and spaces instead of integers

I am currently working on a Sudoku program and I have a test.txt file that contains the following data: 53__7____ 6__195___ _98____6_ 8___6___3 4__8_3__1 7___2___6 _6____28_ ___419__5 ____8__79 In the grid above, each "_" represents a space. This way ...

Reducing Repositioning in Marionette for Better Performance

I'm grappling with a web application that uses Marionette to render complex nested views. The challenge I face is minimizing reflows by ensuring child elements are rendered and placed in parent containers before being inserted into the DOM. How can I ...

Invoking a function through an array within the model where said members are declared

My goal is to consolidate all of my model functionality in one centralized location. I want the ability to access its methods from within the model itself: JavaScript /** * This application displays "OK" a specified number of times based on the button p ...

Is it possible in GDB to configure memory to function like a character array?

Imagine you have a 32-element unsigned char array located at address 0xdeadbeef. Your goal is to change the contents of the array in memory without using the -g compilation option, which prohibits a simple "set [variable name] = [my value]" command. Is th ...

Replace specific columns in a 2-dimensional numpy array using a 1-dimensional array

Consider the arrays: from numpy import * b = ones((5,5)) a = arange(4) How can I efficiently update array b with array a to achieve the following result? array([[ 1., 0., 0., 0., 1.], [ 1., 1., 1., 1., 1.], [ 1., 2., 2., 2., 1 ...

What is the best method to decrease every number in an array by 1?

If I start with a number array as follows: var numberarr = [1, 2, 3, 4, 5]; How can I transform it into the following array by decreasing each element by 1? var numberarr2 = [0, 1, 2, 3, 4]; ...

Leverage the power of jQuery to fetch data from a PHP script connected to a MySQL database

It might be a bit confusing, so let me clarify. I'm working on a form where users input a ticket and it gets assigned to a technician based on the service they offer. I have 3 text fields: username, email, and description of the problem. The next fie ...

Vue.js is not incrementing the counter as expected

I've encountered an issue with a button that has a click event to increment data value by 5, but instead of adding 5 it is appended by 5. Click here for the code example <div id="react"> <button @click='counter += 5'>Increment& ...

Illuminating Wireframes with Three.js MeshPhongMaterial

While attempting to display a mesh with Phong shading along with wireframe on an ArrayBufferGeometry where the vertex colors are set to THREE.vertexColors, I encountered an issue where the lighting only affects one random face. However, when I switch to Me ...

Creating a Nuxt project and integrating the Axios module

I'm running into an issue where I'm not receiving any data from my Axios async calls. I've configured my calls in my Nuxt config as follows: modules: [ '@nuxtjs/axios', ], And in my component, it's set up like this: <tem ...

Obtain elements from an array containing multiple objects

I have a somewhat complex mix of objects and arrays that I need to flatten for easier rendering. The setup involves input fields with an option to add custom fields using a custom label and value. However, in the database, these are stored as 'customL ...