Vue.js - The dissonance between data model and displayed output

Below is a simplified example of my issue:

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>

  </head>
  <body>
    <div id="app">
    <ol>
        <li v-for="series in currentSeries" v-bind:data-id="series.id">
        The ID is <% series.id %>
        <a href="javascript:;" class="removeSeries">X</a>
        </li>
      </ol>
    </div>
  </body>

  <script>
    vueApp = new Vue({
    el: '#app',
    delimiters: ["<%", "%>"],
    data: {
        currentSeries: [{id: "1"}, {id: "2"}, {id: "3"}]
    },

    methods: {
        removeSeries: function(id) {
        this.currentSeries = this.currentSeries.filter(function(element) {
            return element.id != id;
        });
        }
    }
    });

   $(function() {
       $(document).on("click", ".removeSeries", function() {
       var id = $(this).parent().data("id");
       console.log(id);
       vueApp.removeSeries(id);
       });
   });
  </script>
</html>

In the 'currentSeries' variable, I have a list of series displayed as links with an 'X' option to remove them from the list.

The issue arises when clicking on the 'X' button to remove elements. If the first item is removed, it changes its position to be the second one but still displays 'ID 1'. It seems that the data attribute 'data-id' was not updated during rendering. What could be causing this problem and how can I enhance this functionality?

Answer №1

When working with Vue and jQuery, it's important to remember that they are fundamentally different in concept. In this case, using jQuery is unnecessary because you can simply utilize Vue's built-in click event:

// This code will trigger the removeSeries function on click and delete the element based on its ID
<a href="#" @click="removeSeries(series.id)">X</a>

By implementing this, you can call the removeSeries method for a specific id, allowing you to update the model data as needed.

You can find an example of this in action on JSFiddle:

https://jsfiddle.net/vyra5nzc/

Additionally, if you're using Vue alongside another templating engine like Laravel's Blade, keep in mind that Vue also supports @{{data}} as a delimiter option instead of the double mustache syntax.

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

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

I am concerned about the security of my games as they can be easily hacked through right-click inspect. What measures can

As a newcomer to game development, I am creating web games using JS, HTML, and CSS. However, I have encountered an issue with preventing right-click inspect hacking, which has led to people hacking my games through this method. I am wondering, how can I s ...

Utilizing Cookies in an AJAX Request for Cross-Domain Communication with Pure Javascript

I am in the process of developing an Analytics application and I'm seeking a method to uniquely identify each user's device. Currently, my approach involves generating a "cookie" from the server side to track all page clicks and interactions thro ...

What steps can I take to ensure a JavaScript loading image is displayed until the entire page has finished loading?

Looking to implement a JavaScript loading image that displays until the page has fully loaded? I'm currently developing an online antivirus scanner and in need of help. I am trying to set up JavaScript to show a loading image while a file is being up ...

What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite ...

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...

Retrieve a specific item from a JSON response using Node.js

When I receive a message from a WebSocket, the code snippet is triggered like this: ws.onmessage = (e) => { debugger if (e.data.startsWith('MESSAGE')) alert(JSON.stringify(e.data)) ImageReceived(e.data) c ...

Having trouble uploading a file after updating in Vue/Laravel?

My component is functioning properly on the create form but encountering issues on the update form. Although the image displays on the update form, when attempting to upload it, there seems to be no file received for the field 'image' This is th ...

Retrieve information from deeply nested JSON and showcase using Vue-Multiselect

My goal is to fetch data from the server and present it in Multiselect using nested JSON, which can be done through Vue-Multiselect. Once displayed, I should have the ability to add new tags as needed, essentially updating the data. While I can display o ...

Changing the color of a div while implementing a show and hide effect in JavaScript

I have designed a checkout system with three distinct parts - shipping information, billing information, and order confirmation. These sections are all on the same page, allowing for a seamless flow during the checkout process. Once a customer completes t ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

My tests are not passing because I included a compare method in the Array prototype. What steps can I take to fix this issue in either the

Embarking on the challenging Mars Rover Kata has presented a unique problem for me. My jasmine tests are failing because of my array compare method within the prototype. This method is crucial for detecting obstacles at specific grid points. For instance, ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

Implementing a feature in ReactJS that enables users to select a minimum and maximum limit for checkboxes

I have developed a unique React application that incorporates JSON values into checkbox elements. The JSON data includes both minimum and maximum required values. I successfully implemented a function to set the checkboxes' maximum value based on the ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...