简体   繁体   中英

How to change computed object in Vue?

I have simple select 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 main date object stored in Vuex:

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

The problem is that when I change months the month value doesn't change... Visually month in select changed but the value is still the same as it was before.

That's because a computed property, as the name suggests, can only be overwritten internally and it's not a data store that you can write to. If you want to populate your month from the VueX store and retain writability, it is best written as a combination of:

  • a watcher that watches date , and updates the internal month data whenever the store is updated
  • a internal data that simply allows writing and reading of month

An example is as follow:

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

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

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

Of course, following the DRY principle, you might want to abstract 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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM