Exploring the power of utilizing v-model in VueJS to enhance data bindings

Just wondering if anyone else has tried using vue's v-model with a method instead of computed. I stumbled upon this thread: How to bind a v-model with a method in Vue.js which seems to suggest it's not directly possible, but there might be a workaround. I'm currently working with bootstrap vue's datepicker, but I believe the concept can be applied universally.

In my scenario, I have two datepickers:

<b-form-datepicker id="end-datepicker" v-model="formatISO8601Start" class="mb-2 border-0" hide-header></b-form-datepicker>
<b-form-datepicker id="end-datepicker" v-model="formatISO8601End" class="mb-2 border-0" hide-header></b-form-datepicker>

If I had only one date picker, I would probably opt for a computed approach like below:

formatISO8601: {
      get: function() {
          return .....
      },
      set: function(dateSegment) {
          ....
          ....
      }
    },

The dilemma arises when dealing with multiple datepickers sharing the same computed property. Creating individual computed properties for each picker seems redundant and goes against best practices due to code duplication.

My idea is to try using methods instead, by replacing the regular

v-model="formatISO8601"
with:

:value="getISO8601Time('start')" @input="setISO8601Time(????)"

This way, I can dynamically handle the logic based on the parameter passed:

<b-form-datepicker id="end-datepicker" :value="getISO8601Time('start')" @input="setISO8601Time(????)" class="mb-2 border-0" hide-header></b-form-datepicker>
<b-form-datepicker id="end-datepicker" :value="getISO8601Time('end')" @input="setISO8601Time(????)" class="mb-2 border-0" hide-header></b-form-datepicker>

getISO8601Time(time) {
  return ......
}

setISO8601Time(????) {
  ....
  ....
}

However, I'm facing some confusion here. Specifically, the placeholder ???? where the selected date should be captured. In computed properties, the parameter dateSegment in the set function automatically holds the selected date, but this behavior doesn't seem to apply in methods. How can I retrieve the selected date in this context?

Answer №1

Perhaps experimenting with the data function could be a good solution:

new Vue({
  el: "#example",
  data() {
    return {
      start: null, 
      end: null
    }
  },
  methods: {
    setISO8601Time(e, time) {
      e = new Date(e)
      this[time] = e.toISOString()
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<div id="example">
  <b-form-datepicker id="end-datepicker" 
    :value="start" 
    @input="setISO8601Time($event, 'start')" 
    class="mb-2 border-0" hide-header>
  </b-form-datepicker>
  {{ start }}
  <b-form-datepicker id="end-datepicker" 
    :value="end" 
    @input="setISO8601Time($event, 'end')" 
    class="mb-2 border-0" hide-header>
  </b-form-datepicker>
  {{  end }}
</div>

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

Quickly Share Documents within a Folder

I currently have a server set up with the following file structure: - index.js /client -index.html -about.html -signup.html -style.css Within the index.js file, I have implemented an express server. When the user navigates to /, it should display the ...

`The form input status color remains static and does not update`

I encountered a situation in one of my projects where I need to visually indicate if a field is correct or incorrect based on the value of another field. To better illustrate this issue, I have created an example here. The main challenge: I am struggling ...

Obtain the HTTP response status code within a middleware function

I am currently developing an application where I want to create a custom logging system for every request made. For each request, I want to log the timestamp, method, route, and the response code sent to the client. Here is the code I have at the moment: ...

Identifying a selection field problem post implementation of jquery mobile

I recently started using Phonegap and ventured into web development. I was able to successfully implement the HTML select tag in my project, but when I introduced jQuery Mobile, I encountered an issue where the select tag displayed two boxes - one resembli ...

Having trouble retrieving the value of an object in Angular

I have an AngularJS factory named 'userFactory' that I'm using: app.factory('userFactory', function($window) { var auth = { isLogged: false, user: "a", check: function() { if ($window. ...

Guide to decoding JSONP data sent from a remote server

Working on retrieving data using JSONP. After observing the returned data in Firebug, I can confirm that it is being returned correctly. However, I am facing a challenge in figuring out how to parse it. Is the data returning as a nested array? The callback ...

Ways to set the input=text field as read-only in JSP when receiving information from the backend

For a project I am working on, I need to implement a feature where users can view and edit their personal details on a JSP page. If a user is logged in, their information should be fetched from the session and displayed automatically. However, even if they ...

Callbacks for AJAX responses that are asynchronous

After using AJAX in a limited and straightforward manner for some time, I find myself currently debugging a web application that heavily relies on JavaScript and JQuery for client-side coding. One issue that has caught my attention is the possibility of mu ...

Is it possible for the ajax url option to accept an array of URLs rather than just one?

Is there a way to retrieve and store data from multiple JSON URLs in an array? <script type="text/javascript"> urls = ["https://spreadsheets.google.com/feeds/list/1RsiDuydBBHyu4OBjlxq1YH6yT3qcJDMB6-YKU-xxd_k/od6/public/basic?hl=en_US&alt=jso ...

What is the reason for Rich file manager to include filemanager.config.json instead of simply adding an image to the text

I have integrated Rich File Manager with Laravel 5.3.20 using the default configuration provided below: Javascript <script> CKEDITOR.replace( 'textarea', { filebrowserBrowseUrl: '{!! url('gallery/index.html& ...

What is the best way to store article IDs using Javascript or HTML?

On my web page, I have a collection of links that users can interact with by clicking and leaving comments. These links are loaded through JSON, each with its unique identifier. But here's my dilemma - how can I determine which link has been clicked? ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Display the elements of a div at a reduced size of 25% from its original dimensions

I'm currently developing a JavaScript-based iOS simulator that allows users to view their created content on an iPhone and iPad. This involves using AJAX to load the content/page into the simulator, but one issue is that the simulator isn't life- ...

Using NodeJS to generate a multipart/mixed response

I am faced with a particular situation: creating a multipart/mixed response in NodeJS with full control over the communication on both ends to avoid interoperability issues. A JSON file containing a list of nodes describing each ZIP file, for example: [{ ...

Rotating Character in Three.js

I need help adjusting the direction in which a character is facing at spawn in three.js. I referenced an example from to add the character to my scene. While following advice from , I encountered issues with the character controls due to rotation. Curren ...

Alert AngularJS $watchCollection when changes occur in the model being observed by$watch

Currently, I have a $watch function that is listening for an input and then calling a service to retrieve new data. This returned data is essential for another function called $watchCollection. My dilemma lies in finding a way to notify the $watchCollecti ...

Implement checkbox functionality for data binding in Vue framework

I'm having trouble figuring out how to display the selected values in Vue. I've got a form that triggers a query based on the user's selections: <form id="Register"> <br>Firstname<input type="checkbox" value="firstNam ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...

Sharing data between Vue.js v2 components and updating the parent when it's modified

My goal is to create a Form that can identify errors in its Inputs. Despite hours of effort, my current setup, which renders the inputs within a section of the form, is not functioning as intended. What would be the most effective approach to ensure this ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...