Modifying computed object in Vue: A step-by-step guide

My issue involves a simple selection of months:

<select v-model="month" v-on:change="dateChanged('month', month)">
    <option v-for="(month, index) in months" :value="index">{{ month }}</option>
</select>

The primary date object is stored in Vuex:

computed: {
    ...mapGetters(['date']), 
    month() {
        return this.date.format('M') - 1
    },

I'm encountering an issue where when I change months, the value of month doesn't update. Visually, the month in the select changes, but the value remains unchanged from before.

Answer №1

If you're wondering why a `computed` property can't be directly overwritten, it's because it functions as an internal calculation rather than a writable data store. To populate your `month` from the VueX store while maintaining writability, consider using a combination of:

  • a watcher that monitors changes to `date`, updating the internal `month` data when the store is updated
  • an internal data property that permits both writing and reading of `month`

Here is an example implementation:

// Populate internal store with state data
data: function() {
    return {
        month: this.date.format('M') - 1
    }
},

// Map getter
computed: {
    ...mapGetters(['date'])
},

// Watch for changes to mapped getter
watch: {
    date: function(val) {
        this.month = this.date.format('M') - 1
    }
}

To adhere to the DRY principle, consider abstracting the logic into a separate method:

methods: {
    getMonth: function(month) {
        return month.format('M') - 1;
    }   
},
data: function() {
    return {
        month: this.getMonth(this.date)
    }
},
computed: {
    ...mapGetters(['date'])
},
watch: {
    date: function(val) {
        this.month = this.getMonth(val)
    }
}

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

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Implement ng-model on an input field that is pre-filled with a value from a different model within the Angular

One challenge I am facing involves pre-populating an input field with user information, such as their email address or first name, if that data is available. Initially, I set the value of the input field using $scope.userData. However, when I add an ng-mo ...

Troubles arising from JavaScript functions within vue-router

I have implemented a function to authorize users, enabling restrictions on specific components based on their permissions. The function currently works effectively with the 'beforeEnter' navigation guard in Vue Router. However, I am facing diffic ...

Is there a feature in Angular similar to Vue.js's "computed property" functionality?

After mastering Vue.js, I recently dove into Angular 4 for a new project. I've found that most things in Angular are quite similar to Vue, with the notable exception of "Computed Property". In Vue, I could easily create a computed property that would ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...

Integrating Bootstrap-vue into your Webpack setup for seamless usage

After beginning a project with vuejs-templates and webpack, I decided to incorporate bootstrap-vue. Now, the challenge is figuring out how to implement a bootstrap button. In my code base, specifically in main.js, I have imported BootstrapVue: import Vu ...

Perform an AJAX request within a condition prior to executing the subsequent AJAX request

Within my database, I have two tables. When the submit button is pressed, I aim to insert a new trader into the trader table and retrieve the ID using laravel 5.2 by utilizing post ajax under certain conditions. Then, execute another post ajax for invoic ...

Combining jQuery form validation with a PHP script on a single webpage

After implementing jQuery form validation and redirecting using the function btn_onclick() { window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php, my web app's PHP script is not being executed. The user is re ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

Include the names of the routes in the array

Instead of using the <a href> as a string, is it possible to add the route to the array? In this particular case, I am creating a link to update-building and including the buildingId as a parameter. Is there a way to reference the route name for &a ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

Focusing on the combination of Phonegap, Angular JS, and Onsen for app development

We are working on developing an app using PhoneGap, Angular JS, and Onsen. One issue we are facing is that we are unable to center the header in a modal. The code snippet is provided below: <ons-modal var="modalVariable"> <ons-navigator var"de ...

An error is thrown when trying to retrieve Objects: Uncaught TypeError - Object function ParsePromise()

By obtaining a Document object with its id, the following code proceeds to locate corresponding sections based on the object. The document identifies a Parse object and document.toJSON converts this into a Javascript object. Furthermore, sections represent ...

Finding the occurrences of elements in an array using JavaScript

While browsing Stack Overflow, I stumbled upon a question that has yet to be answered: How can I count the occurrences of elements in a specific array using JavaScript?. let array = [6, 1, 5, 1, 1, 8, 2, 4, 6, 0] // Elements in array getOccurrence(array) ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

Having issues with the addClass() method in JavaScript not functioning properly on hover

Coding Challenge <ul class="navBarExtended"> <li><a href="#">Link</a></li> </ul> Styling Solution .onHover{ text-decoration: underline; } Interactive Scripting $("ul.navBarExtended li a").hover( function() ...

Should we bundle everything into one script with webpack, considering Npm and Dev dependency or just dependencies?

Imagine a scenario where we use webpack to bundle all our code into a single JS file, which automatically imports dependencies. In this case, is it necessary to include any dependencies in the package.json, or can they all be listed as --save-dev? Let&apo ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...