Issues with VueJs: Modifications to arrays are not reflected in the DOM

In my model, I am initializing an array after the model is mounted when an AJAX call is successful.

    var self = this;
    $.getJSON("somejson.json",
        function (data) {
            var list = [];
            list = data.list.map(function (item) {
                return { id: item.id, text: item.text };
            });

            self.selectableItems = list;
        });

For each item in the selectableItems array, I have a click method that removes the item.

        select: function (item) {
            this.selectableItems.pop(item);
        },

Initially, selectableItems renders correctly. However, when I modify the array, the DOM does not update accordingly, although the array is updated correctly.

To confirm this, I created a computed property that returns the count of selectableItems. The count updates correctly when an item is removed, but the DOM does not reflect the change.

I also noticed that hard coding the value of selectableItems in the AJAX call results in everything working as expected!

self.selectableItems = [{ id: 1, text: "adsad"}];

While I am aware of the pitfalls of array mutation in Vue, I believe I might be overlooking something simple, as I am relatively new to exploring Vue. Can someone help point out what I may be missing?

Answer №1

Array.pop() is used to remove the last item from an array without any argument. It simply removes the last item from the array without considering any arguments passed to it.

This is why your computed property displaying the array count is affected, as it is removing the last item rather than the specific item you intended to remove.

Instead of using Array.splice(), consider using it.

You can pass the index to your click method this way:

<ul>
    <li v-for="(item, index) in selectableItems" @click="select(index)">{{item}}</li>
</ul>

script

select: function (index) {
        this.selectableItems.splice(index, 1);
    },

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

How to create a clickable link that functions as a file upload button

I am working on a project where I need to create a link that acts as a file input when clicked. Here is the code for the link: <a id="upload-file">Upload your photo</a> Is there a way to make this link function as a browse file input? Any ...

What is the process for configuring sendmail in a node.js environment?

After setting up Sendmail on my Nginx server and configuring SMTP for sending emails in my Node.js project, I still encountered issues with emails not being sent. I tried using Sendmail directly, but I'm unsure of how to properly configure it. Here i ...

Retrieving the data from an AJAX JSON variable

Inside my JavaScript function, I am fetching data like this: var jsonData = $.ajax({ url: "pie_chart_community.php", community_id: $c_id, dataType: "json", async: false }).responseText; Is there a way for me to access the community_id in ...

Ways to send data to nested elements when implementing secure routes?

I am currently working on a project to develop a 'Train Ticket Reservation System' using ReactJS. In order to access the services, users must login, so I have implemented protected routes to render certain components. Instead of relying on the de ...

Displaying components according to ternary conditional operator

I'm currently working on a piece of code that I only want to render when the correct or incorrect answer is given. Initially, I want to display only the question and the possible answers. In React, when the answer is "false", the message "you are wron ...

I am unable to access the information from a .txt file using Ajax

I'm attempting to create a basic AJAX example, but I'm encountering issues getting it to function correctly. Below is the code I have: <script> function loadXMLDoc() { var xmlhttp; if (window.XMLhttpRequest) { ...

Display a message box in the external window just before the close event

I am trying to implement a message box that will appear when the user clicks the (X) button of an Ext window. However, I am facing an issue where the window closes before the message box is shown. Below is the code snippet I have written: var assignReport ...

AngularJS: Double the power of Ajax. Can you assist me?

ajax was successful twice. Take a look. https://i.sstatic.net/QLdpT.png https://i.sstatic.net/zAbXW.png ...

JavaScript - Retrieve all properties and methods of an object

Can an object created through a constructor function have its keys listed using the Object.keys() method? Let's consider an example with the following code: function Foo () {} Foo.prototype.bar = 'bar'; Foo.prototype.baz = 'baz'; ...

How can a JSON string be assigned to a variable for use in a Google pie chart?

I am currently experiencing an issue with my web server. I am sending a JSON object as an argument via render_template to my website, where I intend to use this data to display a Google pie chart. The problem arises when I try to assign the Google pie cha ...

What is causing my switch statement to not align with any cases?

Whenever I implement a switch statement, none of the cases seem to match the 'prefix' value. However, when I switch to using an if-else statement instead, everything functions correctly. What could be causing this discrepancy? Thanks in advance ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Grasping the idea of elevating state in React

I can't figure out why the setPostList([...postList, post]) is not working as expected in my code. My attempts to lift the state up have failed. What could be causing this issue? The postList array doesn't seem to be updating properly. I'v ...

Avoid altering the Vuex store state directly without using mutation handlers in VueJS

I am currently working on developing a listenAuth function that monitors the "onAuthStateChanged" event in firebase to inform the vuex store whenever a user logs in or out. From what I can gather, I am only updating state.authData using the mutation handle ...

Issue Arising During File Transfer in Nativescript

I am currently attempting to upload an image that I captured with Nativescript to a server using a web API that I created in C# (ASP.NET). The API works perfectly fine when tested on Postman, but I encounter an error "Error During Upload" while trying to u ...

Removing elements from a static array in C++

Whenever I initialize an array in this way: int* data = new int[50]; for (int i = 0; i < 50; i++) { data[i] = generateRandomNumber(); } (Populated with random numbers for testing) I release the memory like this: delete[] data; However, if I defin ...

Hot reloading functionality ceases to function within Docker container after a period of time

Scenario In our development setup, we utilize Docker to containerize a Vue.js application and attach a volume with the source code for easy testing and maintenance. Docker Configuration FROM node:13.8-alpine RUN yarn install && \ apk ad ...

Display the name of the link on the console

I am working on an HTML list that contains some links: <ul> <li><a href="#" name="link1">link1</a></li> <li><a href="#" name="link2">link2</a></li> <li><a href="#" name="link3">link3& ...

Is there a method to ensure that the window event always gets triggered before any other events?

Is there a way to make the window event trigger first when clicking on #myDiv? (function ($, w, d) { $(d).ready(function () { $(w).click(function() { alert('window has been clicked'); }); $('#myDiv').cl ...

The issue arises when trying to apply Bootstrap CSS styles to dynamically created elements using JavaScript

I utilized JavaScript to create a Bootstrap Modal and followed the correct classes as outlined in the Bootstrap documentation, but unfortunately, the JavaScript-created elements are not being affected. Even after adding the Bootstrap classes and attribute ...