Using Vue.js along with Vue.set() to update a Key/Value pair array

I am currently exploring the functionality of the

this.$set (also known as Vue.set)
method when updating a multidimensional array.

Take a look at this example:

new Vue({
  el: '#app',
  data: {
    rows:[{"id": "4", "edit": "true" }, { "id": "5", "edit": "false" }] 

  },
....

How can I utilize $this.set to achieve something like this:

this.rows[0].edit = false

I have tried this and it doesn't work:

this.$set(this.rows2, 0, false)

What is the correct approach to using $this.set for an array with key-value pairs?

Answer №1

Given that the properties for editing in your rows objects are already configured, there is no necessity to utilize Vue.set in this scenario. Just assign the property value and Vue will automatically detect the change:

this.rows[0].edit = false;

Below is a straightforward example:

new Vue({
  el: '#app',
  data() {
    return {
      rows:[
        { "id": "4", "edit": true }, 
        { "id": "5", "edit": false }
      ],
    }
  },
  methods: {
    editNext() {
      let index = this.rows.findIndex(r => r.edit);
      
      this.rows[index].edit = false;

      let next = ++index % this.rows.length;
      this.rows[next].edit = true;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <div v-for="(row, i) in rows" v-if="rows[i].edit">
    Editing Row ID {{ row.id }}
  </div>
  
  <button @click="editNext">Edit Next</button>
</div>


However, if the initial state of the edit property in your row objects was not defined (or as a precautionary measure), then employing Vue.set becomes essential to introduce the property and enable reactivity:

this.$set(this.rows[0], 'edit', false);

Here's an illustration of such a situation:

new Vue({
  el: '#app',
  data() {
    return {
      rows:[
        { "id": "4", "edit": true }, 
        { "id": "5" }
      ],
    }
  },
  methods: {
    editNext() {
      let i = this.rows.findIndex(r => r.edit);
      
      this.$set(this.rows[i], 'edit', false);
      
      let next = ++i % this.rows.length;
      this.$set(this.rows[next], 'edit', true);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <div v-for="row in rows" v-if="row.edit">
    Editing Row ID {{ row.id }}
  </div>
  
  <button @click="editNext">Edit Next</button>
</div>

Refer to the documentation on Vue's Change Detection Caveats for more information.

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

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

What is the best method to determine if an object includes a specific string?

While I can read values inside the object as the h tags get populated, for some reason I am unable to hit the statements checking response.image for a value, despite confirming its existence through console.log. I'm not entirely sure if the code belo ...

Implementing react-table version 7 to display dynamic columns and rows fetched from a JSON dataset via an API

Just starting out with react and I have a json api that needs to be displayed as a table on the client side. My plan is to use react-table v7. This is my approach: Use the keys from the data as column Headers and Accessor The json data will be the rows I ...

Prevent running function bodies simultaneously based on user events in JavaScript until a previously triggered execution is completed

When a user clicks on a button in my component, the doSomething function is activated. The issue I am facing is that doSomething takes between 200-1100ms to finish execution and change state. What complicates matters is that when the button is clicked rapi ...

Create a cookie on a subdomain that is accessible by all other subdomains

I have been working on a NextJS project that involves multiple apps on separate subdomains. My objective is to enable single sign-on so that when I log in to one app, I am automatically signed in to all the others. We are utilizing nookies as our cookie ha ...

Is there a way to change ngx-timeago language when the button is pressed?

I was trying to implement ngx-timeago localization. Everything seems to be working fine, but I am struggling with changing the language from German to Spanish when a button is pressed. Here's the template I am using: {{ date | timeago:live}} <div ...

Warning in Vue 3: Production is being disrupted by "tags with side effects"

After recently upgrading from Vue 2 to Vue 3, I encountered a problem in my app where certain parts show a warning in development mode: [Vue warn]: Template compilation error: Tags with side effect (<script> and <style>) are ignored in client ...

jQuery UI Accordion - Adjusting Panel Height to Content Size

Currently, I am utilizing jQuery UI's Accordion feature from http://jqueryui.com/demos/accordion/, and my goal is to adjust it so that it resizes based on the contents of each panel rather than just fitting the largest one. In addition, I am seeking ...

What exactly does the Javascript object syntax signify? (specifically in a Vue script)

Can anyone explain the purpose of this statement and the difference between using const and var? const { SearchIcon } = myApp.icons; I am currently exploring Vue and still relatively new to Javascript. This code snippet appeared in a tutorial example. The ...

Notation for JavaScript UML component diagrams

When creating connections between entities on a UML diagram, the standard notation is the ball-and-socket/lollipop method. Each pair should include the interface implemented. However, since my project is in JavaScript and doesn't have interfaces, I am ...

The Challenge of Page Refresh in Express and Node.js

I am new to web development and servers, having only taken one course in university. I am facing a strange issue with a GET request where it stops being sent after multiple refreshes. Here is the output from npm start when it is working: GET / 304 0.350 m ...

Can the execute_script function in Python Selenium wait for JavaScript content to fully load before proceeding?

I am currently working on automating a task using Python and Selenium for the Safari browser. The task involves navigating a webpage where clicking on letters from A to Z activates a Javascript function on the page, reloading a table below with stocks that ...

I have developed a function that adds up price values, but for some reason it is always lagging one step behind

I am facing an issue with my React container that has add and subtract functions. These functions are triggered whenever a user clicks on '+' or '-' spans, to calculate the total 'price' of three different 'products' ...

A collection of dropdown fields sharing identical names but containing distinct IDs

I am looking to create an array of select fields with the same list of option values. The goal is to prevent a value that is selected in one field from appearing in another field. For example, if "a" is selected in the first field, it should not be avail ...

Looping infinitely through Navigation Guards beforeEach

Having trouble implementing navigation guard in my code. When I use next('/auth/login'), it results in an infinite loop: router.beforeEach((to, from, next) => { auth.validate().then((valid) => { if (!valid) { next('/auth/l ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

Incorporating PHP variables within JavaScript

As a beginner in web development, I am working on creating an application that heavily relies on JavaScript but also includes PHP/MySQL to prevent users from viewing quiz answers by inspecting the page source. The key pages involved in this project are: in ...

Detecting Changes in Angular Only Works Once when Dealing with File Input Fields

Issue arises with the file input field as it only allows uploading one file at a time, which needs to be modified. Uploading a single file works fine. However, upon attempting to upload multiple files, it appears that the "change" handler method is not tr ...

The data that was returned has the type of "Promise {<Fulfilled>: Array(1)}"

Could someone please assist me in understanding why this code snippet is not functioning correctly? const handleFetchPrices = async () => { // This function fetches prices for all items in the shopping list const promises = shoppingList.map(i ...

Unlocking the document instance in TypeScript: A comprehensive guide

Looking at the current project, there is a decision to rewrite it in Angular 6. One of the components in the project is a side navigation panel which is currently implemented with JavaScript code (found on some website). Since I'm not very proficient ...