Update the DOM if the index of any data elements have been modified

Can Vue.js detect the swapping of array elements in my data object?

data: {
  list: [
    'Foo',
    'Bar',
    'Test'
  ]
}

This is the method I am using to swap entries:

swapIndex: function(from, to) {

  var first = this.list[from];
  this.list[from] = this.list[to];
  this.list[to] = first;

}

Check out the JsFiddle at this link.

If I swap the indices, I want to re-render the v-for loop. Any suggestions on how to achieve this?

Appreciate any help. Thank you!

Answer №1

Here is my unique solution that I have come up with. In order to modify the list, I decided to create a duplicate of the original list and then used the this.$set() method to make the necessary changes:


new Vue({
    el: '#app',
    data: {
        items: [
            'Apple',
            'Banana',
            'Orange'
        ]
    },
    methods: {
        switchItems: function(fromIndex, toIndex) {
            var duplicate = JSON.parse(JSON.stringify(this.items));
            var firstItem = duplicate[fromIndex];
            duplicate[fromIndex] = duplicate[toIndex];
            duplicate[toIndex] = firstItem;
            this.$set(this, 'items', duplicate);
            console.log(this.items);
        }
    }
})

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

Issue with displaying errors in vee-validate when using Vue.js Axios (More details provided)

When working on my Vue project, I encountered an issue while using Vee-Validate and Axios. During an API call to register a user, if the email is already in use, an error is thrown. To handle this error and display the error message, I used the following ...

The absence of a template or render function in a Vue.js 3 and Quasar 2 component has resulted in an

I am currently working on creating a dynamic component and passing a prop to it. However, I am encountering a warning message that says: Component is missing template or render function. Although the component is being rendered, I am still receiving the wa ...

What is the best way to utilize Object.keys for formatting incoming data?

Here is the data I have: const langs = { en: ['One', 'description'], pl: ['Jeden', 'opis'], }; I want to convert it into this format: const formattedData = { name: { en: "One", ...

Leveraging the power of the 'var' keyword in JavaScript when

I have a javascript code snippet that looks like this: var grade_type = document.getElementById("grade_type").value; gradesRef.set({ grade_type: firebase.firestore.FieldValue.arrayUnion(grade) }); However, when the data is stored i ...

Attempting to conditionally map an array of objects

I am currently working on conditionally rendering content on a screen. My main task involves manipulating an array of 3 objects with sub-objects, stored as the initial state in my reducer (using dummy data). The layout includes a customized SideNav bar wit ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

Trigger event when user ceases to click

I have successfully implemented a click event using jQuery. Here is the code: $('#myButton').click(function(){ // perform desired actions }); However, I am facing an issue where multiple intermediate events are triggered if the user clicks on ...

Emphasize the URL of the current page and navigate up one level

I have a list of links in my navigation. I want the current page's link to be highlighted, as well as the parent page's link one level up. For example: All pages: /blog, blog/careers, blog/authors Page: /blog/author Highlight: /blog/author, /blo ...

What is the best way to create a blurred effect on an image during loading, and then transition to a sharp image once it is fully loaded?

I'm currently working on a project where I want the images to display as a blurred preview initially, and then become clear once fully loaded. This is similar to the feature seen on Instagram, where the app shows a blurred image before displaying the ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Hiding and showing div elements using CSS, JavaScript, and PHP

Here is the current code snippet: <? while ($row1 = mysql_fetch_object($result1)) { echo '<a href="#" onclick="showhide("'.$row1->id.'");">Name</a>'; while ($row2 = mysql_fetch_object($result2)) { ...

Monitoring a folder using webpack

Currently, I have webpack set up in my development environment to bundle all of my dependencies. To help concatenate various js files and include them in a script tag within the markup, I am utilizing the webpack-merge-and-include-globally plugin. Althoug ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Columns that can be resized in a right-to-left (

Whenever I use RTL, the columns behave erratically when resizing... I have implemented colResizable. You can see an example here: http://jsfiddle.net/r0rfrhb7/ $("#nonFixedSample").colResizable({ fixed: false, liveDrag: true, gripInnerHtml: "<d ...

Caution: It is important for every child in a list to have a distinctive "key" prop value. How can a shared key be used for multiple items?

When I click on a header from my list, an image should appear. However, I'm encountering an error that needs to be resolved. I've been struggling to find a solution for adding unique keys to multiple elements in order to eliminate the error. Des ...

Discover the syntax for reading route parameters in Angular

Currently, I am integrating the Paypal API into my project. After confirming a purchase, Paypal redirects to a specified URL. I set the desired URL as "localhost:4200/shop/order". However, when Paypal returns the URL, it appends the token and payerid at th ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

Call upon the prototype method of the parent class

"I'm having trouble understanding a piece of my code: //constructor function Widget (options) { }; //return the string Widget.prototype._addEditFormString = function (val) { return "<in ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...