1

我有Vuex全局日期对象的简单模块:

import moment from 'moment';

const state = {
    date: moment()
}

// getters
const getters = {
    date: state => state.date,
    daysInMonth: state => state.date.daysInMonth()
}

// mutations
const mutations = {
    subtractOneDay(state) {
        state.date.subtract(1, 'days');
    }
}

export default {
    state,
    getters,
    mutations
}

我的子组件之一:

import { mapGetters, mapMutations } from 'vuex';

export default {
    computed: Object.assign(mapGetters(['date', 'daysInMonth']), {}),
    methods: {
        subtractOneDay() {
            this.$store.commit('subtractOneDay');

            console.log(this.date.format('YYYY-MM-DD'), this.date.daysInMonth(), this.daysInMonth)
        }
    },
    created() {
        console.log('blocks created')
    },
    mounted() {
        console.log('blocks mounted')
    }
}

基本上我需要在更改时获得一个月中的几天(29、29、30 或 31)date

问题是计算属性daysInMonth不会改变......

4

1 回答 1

2

Moment 的subtract方法改变了引用的 moment 对象。这对 Vue 来说是个问题,因为这意味着对 的引用没有state.date改变,并且计算的属性不会重新计算它们的值。

您可以使用 moment 的clone方法来解决此问题,以在该方法中返回一个新的时刻subtractOneDay

这是一个例子。

console.clear()

const store = new Vuex.Store({
  state:{
    date: moment()
  },
  getters:{
    date: state => state.date,
    daysInMonth: state => state.date.daysInMonth()
  },
  mutations: {
    subtractOneDay(state) {
        state.date = state.date.clone().subtract(1, 'days');
    }
  }
})

new Vue({
  el: "#app",
  store,
  computed: Object.assign(Vuex.mapGetters(['date', 'daysInMonth']), {}),
  methods:{
    subtractOneDay(){
      this.$store.commit('subtractOneDay');
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  {{date}}
  <hr>
  {{daysInMonth}}
  <hr>
  <button @click="subtractOneDay">Subtract 1 Day</button>
</div>

于 2018-05-04T13:38:21.583 回答