Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js modify computed property?

Tags:

I am trying to modify a moment.js instance that resides in vue.js computed property like so.

computed: {
    currentDate() {
        return moment();
    }
}

Whenever I try to call it with a method like this one, nothing happens:

methods: {
    prevMonth() {
        this.currentDate = moment(this.currentDate).subtract(1, 'months');
    }
}

I am guessing this is because computed properties only allow to act as getters(and optionally setters). How can I change this behavior though?

I oversimplified the example since I am using the cmoputed property to fetch data from my vuex store. I am no longer able to manipulate it though.

Is there some way I can populate a local currentDate property with the vuex store's value so I can still manipulate it and add months, etc?

I have though about using the mounted property for this but I only mount my component once. Any help is welcome.

like image 241
Stephan-v Avatar asked May 09 '17 10:05

Stephan-v


2 Answers

If your currentDate property belongs to your Vuex store, you shouldn't be manipulating it inside your components. You should instead: 1) map the getter locally as a computed property and 2) map the mutation locally as a method.

Here's an example of what your date Vuex module might look like:

export default {
    state: {
        currentDate: moment()
    },
    mutations: {
        subtractMonth (state, date) {
            state.currentDate = moment(state.currentDate).subtract(1, 'months');
        }
    },
    getters: {
        getCurrentDate: (state) => {
            return state.currentDate
        }
    }
}

And this is how the component would make use of it, without actually doing anything "locally":

import { mapGetters, mapMutations } from 'vuex'
export default {
    computed: {
        ...mapGetters({
            currentDate: 'getCurrentDate'
        })
    },
    methods: {
        ...mapMutations({
            prevMonth: 'subtractMonth'
        })
    }
}

You'd still be able to bind currentDate inside your component and call prevMonth as before, but now everything is being done via the Vuex single state.

like image 123
Tomas Buteler Avatar answered Sep 23 '22 11:09

Tomas Buteler


Computed properties are not methods, that you can call. If you want to have such method, move currentDate to methods. The you also can invoke it from mounted.

like image 41
Staszek Avatar answered Sep 22 '22 11:09

Staszek