After the computed property is activated, the input values become vacant

I encountered an issue while working on a Vue js project. In this project, I have a computed property named total, which calculates the sum of a property called monto in an array named cobrosMarcados. This array is populated when I click a checkbox in the cobros array. However, the problem arises when I have two input date-rangepickers linked to Vue component data variables. Whenever the computed property is triggered, the input values in the date-rangepickers are reset and become empty.

Below is the Vue js code snippet:

new Vue({
   el: '#app',
   data: {
     cobros: [
        {id:1,nombre:"Mantenimiento",monto:2000},
        {id:2,nombre:"Piscina",monto:2000},
        {id:3,nombre:"Seguridad",monto:2000},
     ],
     cobrosMarcados: [],
     montoPagado: 0,
     vueltoNegativo: false,
     fechaInicial: '',
     fechaFinal: ''
   },
   computed:{
        total(){
            return this.cobrosMarcados.reduce((total, item) => {
                return total + Number(item.monto);
            }, 0);
        },
        vuelto(){
            let vuelto = this.montoPagado - this.total;
            this.vueltoNegativo = vuelto < 0;
            return vuelto;
        }
    },
    methods:{
        addCobro(index){

            let item = this.cobros.find(o => o.id === index);
            let found = false;

            for (let i = 0; i < this.cobrosMarcados.length; i++) {
                if(this.cobrosMarcados[i].id === item.id){
                    found = true;
                    this.cobrosMarcados.splice(i,1);
                    break;
                }
            }

            if(!found){
                this.cobrosMarcados.push({
                    id: item.id,
                    nombre: item.nombre,
                    monto: item.monto
                });
            }
        }
    }
  })

For the full code implementation, you can visit the following link: https://jsfiddle.net/alonsourena/syLrqekm/

I would greatly appreciate any assistance on resolving this issue. Thank you.

Answer №1

When working with input elements, it's recommended to use v-model instead of v-bind.

For example, you can use

<input type="text" class="input-sm form-control" id="fechaInicial" name="fechaInicial" v-model="fechaInicial"/>

For more information, check out: https://v2.vuejs.org/v2/api/#v-model

UPDATE: Another issue you pointed out is that the datepicker component being used doesn't integrate well with Vue.

To address this, you can either a) switch to a different date picker, or b) replace v-model with v-on:blur and create a function to manually update the values.

Take a look at this example: https://stackblitz.com/edit/js-bth9j8

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

Divide the Array into Vertical Arrays

Here is my current result: [ '1', '1', '0', '0' ], [ '2', '4', '0', '0' ], [ '3', '7', '0', '0' ], [ '4', '0&apo ...

Vue, socket.io and Express Session all reset with each new page load

I am currently working on developing a basic application with a login feature to experiment with socketio, vue, and nodejs (express). I have successfully implemented sending and receiving functionality on both the client and server sides. However, I am fac ...

I am experiencing a problem where my webpage does not load properly when trying to access it

After setting up a route triggered by a specific click event using AJAX, I noticed that although my route is being called, the page content is not rendered as expected. Here is my AJAX function: function showProfile(user_id) { console.log("show pro:" + u ...

What is the purpose of adding "/dist" to the library import statement?

Currently, I am in the process of developing a react component library using vite as my primary build tool. After successfully compiling the project and deploying it to the npm registry, I encountered an issue when importing it into my client app. Specifi ...

Pass a JavaScript array variable to a PHP script utilizing jQuery Ajax and receive a string output instead of an array

Whenever I attempt to transmit a JavaScript array to a PHP script via Ajax, the output of $_POST['file_paths'] when var_dumped shows up as a string instead of an array. My goal is to have the output in array format rather than in string format. C ...

Enhancing the appearance of HTML code within x-template script tags in Sublime Text 3 with syntax highlighting

I recently updated to the latest version of sublime text (Version 3.1.1 Build 3176) and have encountered a problem with syntax highlighting for HTML code inside script tags. Just to provide some context, I'm using x-template scripts to build Vue.js c ...

Tips for inserting characters at the cursor in a contenteditable element?

Is there a way to simulate typing a character in either JQuery or plain JavaScript? I am working with a contenteditable section where I need to intercept user input to replace certain characters (such as straight quotes with curly ones). While I have foun ...

Remove the </div> text and replace it with nothing

I'm attempting to substitute the end tag div with an empty string. Here is my code: $('#textDiv').html().replace(/'</div>'/g,'').replace(/<div>/g,'\n') This is the HTML: <div id='tex ...

How can I access data from a function that is executed within a method in Vue.js?

When working with vuejs and JS scopes, passing a value to a style property inside data can be tricky. The issue arises when trying to access this.data.property: Vue.component ('loader-component', { template: '#loader-template', mo ...

How to make Jquery skip over elements with a particular data attribute

I am looking to select all elements that are labeled with the 'tag' class. Once these items have been selected, I would like to remove any items from the list that contain the attribute 'data-tag-cat'. var tags = $('.tag'); c ...

Using Omit<T,K> with enums does not yield the expected result in Typescript

The setup includes an enum and interface as shown below: enum MyEnum { ALL, OTHER } interface Props { sources: Omit<MyEnum, MyEnum.ALL> } const test: Props = { sources: MyEnum.ALL } // triggering a complaint intentionally I am perplexed b ...

HTML Scripts: Enhancing Web Functionality

I have another question regarding executing a script (docs()) upon clicking on text. I attempted to use the following code: <p><span class="skill">Documentation can be found here.<script>docs()</script></span></p> Unfo ...

The functionality of Vue.js routes is disrupted when employing the router-link component

I recently worked on a project using Vue.js. In the navbar, I added two menu options - Home and About, which are supposed to direct users to specific pages when clicked. Everything runs without any errors, but for some reason, the router doesn't navig ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

Storybook is pulling fonts from an incorrect location on the server

Regrettably, I am facing an issue where the fonts do not load when accessing a page with Quasar integration. In the Developer Tools, it shows a path error like this: http://localhost:6006/undefined/node_modules/@quasar/extras/roboto-font/web-font/KFOmCnqEu ...

What is the best way to include an event listener within the `setup` function?

With the switch to vue3, the $on method has been deprecated. In order to add an event listener, it is now necessary to write it directly on the element itself. <transition name="fade" @after-enter="afterEnter"> <div>foo ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...

Here is a way to attach a function to dynamically generated HTML that is returned in an AJAX request

As I was working on a new function development project, I encountered a situation where I had to add a function to dynamically generated HTML through an ajax call. The following is a snippet of the code: $.ajax( 'success': function(data){ ...

Invoke a function within an HTML element inserted using the html() method

Looking for help with a JavaScript function: function toggle_concessions(concessions) { var text = "<table>"+ "<tr><td class='concession-name'>gfhgfbfghfd</td><td class='op-encours&a ...

After the modal is closed, the form object becomes devoid of any content

Having two forms in separate modals has led to an interesting observation. Upon opening the first modal, I successfully log the form attached to $scope. The controller initially assigns $scope.updateSecurityForm = {} with the name attribute as name="update ...