Strategies for saving formatted data in an Array within Vue components - overcoming the limitations of watch and v-model for preserving formatted data

I need to store formatted data from multiple text boxes in an array. Each textbox should display and save the value in m:ss format (m - minute, s - seconds).

Currently, all textboxes show the same value because there is only one this.formatTime variable.

How can I modify this so that v-model iterates through the array and saves the formatted values into an array?

The textbox should display the formatted value and save it in allFormatValues[].

I'm struggling with this issue, appreciate your assistance!

<div id="app">
   <div
      v-for="(input, index) in valueInputs"
      :key="index"
    >
     <input
         v-model="formatTime" //wish to use allFormatValues[index] instead
         id="time-input"      //but lose formatting if changed to above
         type="text"
     />
  </div>
</div>

And

 watch: {
   formatTime () {
      const totalLength = this.formatTime.length;
      let a = this.formatTime.replace(/[^0-9]/g, "")
        .substr(0, 1);

      const b = this.formatTime.replace(/[^0-5]/g, "")
        .substr(1, 1);

      const c = this.formatTime.replace(/[^0-9]/g, "")
        .substr(2, 1);
      if (totalLength >= 2) {
        a = `${a.substring(0, 1)}:${b}${c}`;
      }
      this.formatTime = a;
    },
}

I have an array where I want to browse and assign this value

data () {
  return {
  valueInputs: [],    // a list of inputs
  allFormatValues: [] // intend to keep all the formatted values here by their respective indexes
 }
}

Answer №1

To update the <input>'s value as you iterate, you can connect it to the iterator and implement an event handler that triggers formatTime() in order to update valueInputs:

  1. Connect <input>.value to the input variable:

    <input :value="input" ...>
    
  2. Add an input-event handler on the <input>, which will take the iterator index and the event value as parameters:

    <input @input="formatTime(index, $event.target.value)" ...>
    
  3. Adjust the formatTime() method to accept the index and $event.target.value, and employ vm.$set() to dynamically update valueInputs[index] with the new value:

    export default {
      methods: {
        formatTime(index, input) {
          const totalLength = input.length;
          let a = input.replace(/[^0-9]/g, "").substr(0, 1);
    
          //...
    
          this.$set(this.valueInputs, index, a)
        }
      }
    }
    

Check out the demo here

Answer №2

To optimize the code, consider using computed properties.

Start by ensuring that your input modifies the original value.

<input v-model="input"
       id="time-input" 
       type="text"/>

Next, for better organization, implement a formatValue method:

methods: {
    formatValue(value) {
        const totalLength = value.length
        let a = value.replace(/[^0-9]/g, "")
            .substr(0, 1)

        const b = value.replace(/[^0-5]/g, "")
            .substr(1, 1)

        const c = value.replace(/[^0-9]/g, "")
            .substr(2, 1)
        if (totalLength >= 2) {
            a = `${a.substring(0, 1)}:${b}${c}`
        }

        return a
    },
}

Lastly, create a computed property to handle the formatted values:

computed: {
    formattedValues() {
        return this.valueInputs.map(value => this.formatValue(value))
    }
}

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

Tips for automatically aligning the camera to a specific point in three.js

Is there a built-in feature in three.js for automatically focusing a camera on a specific point, causing the rest of the environment to blur like in these examples? The XG library code that enables auto focus looks something like this: renderer.dofEnable ...

Attempting to utilize regular expressions to substitute HTML tags

I am working on a task to substitute <script type='text/javascript'>some stuff</script> with: <div type='text/javascript'>some stuff</div> My current testing method involves: alert( o.replace( /(?:<\ ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Having trouble with the nav-item dropdown functionality on Laravel Vue?

Currently utilizing Laravel and Vue.js along with AdminLTE. Initially it was functioning properly, but now... head <!-- Font Awesome Icons --> <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css"> <!-- Theme style --> ...

The Vue 3 router seems to be malfunctioning and I am quite puzzled as to why

As someone new to Vue (specifically Vue 3), I decided to test a mock Vue application. After successfully testing the default homepage, I wanted to explore creating multiple pages. Despite following tutorials step by step, I've encountered an issue whe ...

Displaying individual attributes of objects through v-for loop

I have created a table-making component to streamline the process of creating multiple tables. Each table consists of three key elements: The object (an array of objects with one row per object) Headers specific to each table The object properties that n ...

What is the best way to ensure that all the divs within a grid maintain equal size even as the grid layout changes?

I have a grid of divs with dimensions of 960x960 pixels, each block is usually 56px x 56px in size. I want to adjust the size of the divs based on the changing number of rows and columns in the grid. Below is the jQuery code that I am using to dynamicall ...

Utilize Electron's fs to stream a file directly to an HTML video player while it is being downloaded

I am currently exploring the possibility of using the HTML video player to stream a file from the file system within Electron. My goal is to initiate streaming while the file is still being downloaded. I am uncertain whether my current approach will be ...

Replicate and customize identical object for creating instances in JavaScript

I am working with an object that has the following structure: var customObject = function() { this.property = "value"; }; customObject.prototype = new otherObject(); customObject.prototype.property2 = function() {}; This is just a snippet as the ac ...

Result of an asynchronous function

I am facing an issue where the results are being displayed on the console instead of the web browser. Can someone guide me on how to get async results properly? The getAsset() function contains an async operation using getAssetById(), which is functionin ...

Error: The function exec in matchExpr[type] is not defined

I made some changes to Object.prototype and now I'm running into errors with jQuery's methods on selectors. The error message I'm getting is: Uncaught TypeError: matchExpr[type].exec is not a function Additionally, when trying to use $.po ...

Tips for customizing the color of the inner components in the toolbar of MUI DataGridPro

Is there a way to customize the color of the inner components in mui toolbars? For example, I have added columns and when I click on them, a filter box pops up with default colors for switches and buttons. How can I change these colors to match my theme? ...

Tips on saving the background image URL value into a variable

How can I save the URL value of a background image in a variable? For example: image: url(images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg); I store this value as value = images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg in a variable and then use this variable in an href tag. ...

Transferring Data from Python Script to Browser (with an xserver running on a Linux system)

Looking for suggestions on how to efficiently transfer data from a Python script to a web browser. The Python script, as well as the browser, are operating under an xServer environment in Linux (specifically Raspbian on Raspberry Pi). The script is respon ...

What is the best way to initiate an event using the onMousewheel function?

I am currently working on a WebGL application where I have a sphere object that utilizes orbit controls for zooming in and out. My goal is to set up an event for the mousewheel so that when I zoom on the WebGL block, the corresponding map location also zo ...

`Accessing information within a nested JSON array``

I'm currently parsing through the JSON data below. While I can extract the id and name fields without any issues, I am encountering a problem when trying to access json.templates[i].dailyemails.length, as it always returns 0. Below is the structure o ...

Using jQuery to Send Data Back to Parent Popup Window

Is there a way to achieve the following functionality with jQuery: create a popup window that sends a value back to the main window when a link in the popup is clicked, then closes the popup and automatically submits a form in the main window based on the ...

When attempting to log an AJAX/JSON request, the console.log statement is displaying 'undefined'

Being new to AJAX, I have encountered an issue that I believe others may have faced as well. Despite numerous attempts and extensive research, I am unable to find a solution to this error. I am confident that it is something simple. Any help would be gre ...

Removing and shattering data from a JSON file at a designated location in AngularJS

I have received json data that is structured like this (and unfortunately cannot be modified): Desc: First data - Second data My current method of displaying this data involves using the following code: <div ng-repeat="b in a.Items">{{b.Desc}}< ...

What is the best way to build a Div structure using a JavaScript Array?

I am currently attempting to create a simple div construct based on a JavaScript array. However, my current approach only displays the last group/element of the array. What adjustments need to be made in order to generate a repeating div construct for each ...