How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the set function for date being executed, and I can observe the dateTime object changing from Vue dev tools. However, the computed date getter does not update - it remains at the initial value. What mistake am I making?

export default {
  ...
  data: function() {
    return {
      ...
      dateMenu: false,
      dateTime: new Date(),
    };
  },
  computed: {
    date: {
      get() {
        return this.dateTime.toISOString().substr(0, 10);
      },
      set(val) {
          this.dateTime.setFullYear(
          val.substr(0, 4),
          Number(val.substr(5, 2) - 1),
          val.substr(8, 2)
          );
      }
    },
    time: {
      get() {
        return this.dateTime.toISOString().substr(11, 5);
      }
    }
  }
}
    <v-menu
    v-model="dateMenu"
    :close-on-content-click="false"
    transition="scale-transition"
    offset-y
    >
    <template v-slot:activator="{ on }">
      <v-text-field
        v-model="date"
        readonly
        v-on="on"
      ></v-text-field>
    </template>
    <v-date-picker
      v-model="date"
      @input="dateMenu = false"
    ></v-date-picker>
  </v-menu>

Answer №1

When attempting to update the value of an existing Date object, it's essential to remember that Vue does not automatically detect these changes. To ensure an update is triggered, you must assign a new Date object to the variable dateTime:

set(val) {
  this.dateTime = new Date(
    this.dateTime.setFullYear(
      val.substr(0, 4),
      Number(val.substr(5, 2) - 1),
      val.substr(8, 2)
    )
  );
}

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

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

Binding Font Awesome icons in Vue.js

Recently, I made some changes to my code that is similar to the Simon game. Initially, everything was running smoothly with buttons for the arrows and using the @mousedown event. However, in an attempt to enhance the appearance by incorporating font awesom ...

Enhance a DOM element using personalized functions in jQuery

Seeking advice on how to create custom widget placeholders with a "setvalue" function specific to each type of widget: $.fn.extend($(".dial"), { setval: function(val) { }); Attempting to avoid extending jQuery.fn directly since different widget type ...

"Local Vue App service functions as expected, but encounters issues when deployed on an Apache

My Vue App runs smoothly on localhost when I run npm run wc. However, once I migrate it to the server, I encounter an error. The error message is as follows: Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For r ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Can you explain the functionality of sinon's stub.yields method?

The explanation given in the documentation for sinon regarding stub.yields is as follows: By using stub.yields([arg1, arg2, ...]), you are essentially performing a function similar to callsArg. This will result in the stub executing the first callback it ...

What is the best way to align a modal with a layout when it appears far down the components hierarchy?

Struggling with creating a React modal and facing some issues. Let's consider the structure below: React structure <ComponentUsingModal> <Left> <ButtonToActivateModal> ... </ButtonToActivateModa ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Update the image and heading simultaneously when hovering over the parent div

I am looking to enhance the user experience on my website by changing the color of headings and images when a user hovers over a specific section. Currently, I have been able to achieve this effect individually for each element but not simultaneously. Any ...

Having trouble serving compressed files efficiently with Express

I'm running into a problem with serving my gzipped webpack bundle. Whenever I try to serve it, I encounter the dreaded ERR_CONTENT_DECODING_FAILED error on the client-side. Here's a snippet of my middleware setup: `app.get('*.js', func ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

Tips for utilizing Angular Js to redirect a webpage

Can someone help me figure out how to redirect to another page using Angular Js? I've searched through various questions here but haven't found a successful answer. This is the code I'm currently working with: var app = angular.module(&ap ...

Utilize RequireJS to modularize scripts in an organized manner

Recently, I was working on a web application and wanted to organize it into modules. After some research, I discovered that RequireJS is the most suitable tool for this task. By reading documentation and tutorials, I managed to come up with the following c ...

Searching for JSON data in JavaScript

Is there a more efficient approach for searching data in JSON other than using loops? This is specifically for editing and deleting purposes. for(var k in objJsonResp) { if (objJsonResp[k].txtId == id) { if (action == 'delete') { obj ...

Issue encountered with Express.js and connect-mongo session: "TypeError - Unable to access property 'upserted' as it is undefined"

I'm working on implementing session storage using the connect-mongo module, but I keep encountering the following error: TypeError: Cannot read property 'upserted' of undefined Here is how I'm using the connect-mongo: import session ...

The JavaScript exec() RegExp method retrieves a single item

Possible Duplicate: Question about regex exec returning only the first match "x1y2z3".replace(/[0-9]/g,"a") This code snippet returns "xayaza" as expected. /[0-9]/g.exec("x1y2z3") However, it only returns an array containing one item: ["1"]. S ...

Invoking a function means calling another one simultaneously

There are two buttons in my code: The button on the right triggers a function called update(): <script> function update(buttonid){ document.getElementById(buttonid).disabled = true; event.stopPropagation(); var textboxid = buttonid.sli ...

Can someone please explain how to use the prevState in REACT?

Can you explain the difference between how to define the counterHandler function in these two examples? counterHandler = () => { this.setState(() => { return { times: this.state.times + 1 } }); } versus counterHandle ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...