首页 > 解决方案 > 使用 vuex 给定项目更新数据

问题描述

我为这样的预订创建了一个模块,这是我的 vuex 商店:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = {
  reservations: [],
  stats: {
    pending: 0,
    confirmed: 0,
    cancelled: 0  
  } 
};

const actions = {
    
    fetchReservations({commit}){
        axios.get('/reservations').then(({data})=>{
            commit('setReservations', data);      
        }).catch(error => {
            throw new Error(error);
        });
    },
    
    deleteReservation({commit}, reservationId){
        axios.delete('/reservations/'+ reservationId).then(()=>{
            commit('removerReservationInList', reservationId);      
    });
    },

    confirmReservation({commit}, reservationId){        
     axios.patch('/reservations/'+ reservationId +'/confirm').then(({data})=>{                                              
       commit('updateReservationInList', data);  
    });     
    },

    cancelReservation({commit}, reservationId){     
    axios.patch('/reservations/'+ reservationId +'/cancel').then(({data})=>{                                                
      commit('updateReservationInList', data);
    });     
    },

    fetchReservationStats({commit}){    
      axios.get('/reservations/stats').then(({data})=>{                                              
      commit('setReservationsStats', data);              
     });     
    }

};

const mutations = {  

  setReservations(state, reservations) {
    state.reservations = reservations;    
  },

  removeReservationInList(state, reservationId){
        state.reservations = state.reservations.filter((reservation)=>{
            return reservation.id !== reservationId
        });
  },

  updateReservationInList(state, data){
    state.reservations = state.reservations.map(reservation => {        
      if (reservation.id !== data.id) {
        return reservation;
      }     
      reservation.state_id = data.state_id;      
      return reservation;
    });
  },

  setReservationsStats(state, data) {    
    state.stats = data;
  }

};

const getters = {
  reservationsList(state){
    return state.reservations
  },
  reservationsStats(state){
    return state.stats;
  }
};

export default new Vuex.Store({
    state,  
    actions,
    mutations,
    getters
});

这些是保留:

[
    {"id":1,"name":"Rollin Koss","email":"predovic.wyatt@example.net","state_id":2, "booking_date":"2020-12-12","number_of_guests":3},    
    {"id":2,"name":"Kellie Schroeder","email":"nicolette39@example.com","state_id":1,"booking_date":"2020-12-02","number_of_guests":14},    
    {"id":3,"name":"Autumn Goldner IV","email":"vkutch@example.org","state_id":3, "booking_date":"2020-12-15","number_of_guests":14}    
    .....    
]

所以,我在其他请求中得到了统计数据。我正在考虑以另一种方式来做,例如,当我得到预订时,返回这样的统计数据:

    [
            "reservations": [
                {"id":1,"name":"Rollin Koss","email":"predovic.wyatt@example.net","state_id":2, "booking_date":"2020-12-12","number_of_guests":3},    
                {"id":2,"name":"Kellie Schroeder","email":"nicolette39@example.com","state_id":1,"booking_date":"2020-12-02","number_of_guests":14},    
                {"id":3,"name":"Autumn Goldner IV","email":"vkutch@example.org","state_id":3, "booking_date":"2020-12-15","number_of_guests":14},
            ....
            ....
            ],
            "stats": {
                "pending": 50,
                "confirmed": 30
                "cancelled": 10      
            }
    ]

state_id = 1 用于挂起的预订,state_id = 2 用于确认的预订,state_id = 3 用于取消的预订

然后例如,当我将待定预订更新为已确认时,待定应减少而已确认应增加,如果已确认预订被取消,则统计信息应反映,此外,如果删除某些预订,例如待定,那么它应该减少,我不知道该怎么做。谢谢你。

标签: javascriptvue.jsvuex

解决方案


除了将统计信息存储为状态对象之外,您还可以使用对您的预订状态作出反应的 getter。

getters: {
stats(state){
  return {
    pending: countState(1),
    confirmed: countState(2),
    cancelled: countState(3),
  };

  function countState(stateId){
    return state.reservations.reduce((acc, cur) => (cur.state_id === stateId ? ++acc : acc), 0);
  }
}

编辑:如果您希望它反映您当前的分页预订,您可以使用计算函数将统计代码从 vuex 移动到组件本身,如下所示:

computed: {
    stats: function () {
        // This should point to your current set of paginated reservations
        const reservations = this.$store.getters.reservations;

        return {
            pending: countState(1),
            confirmed: countState(2),
            cancelled: countState(3),
        };

        function countState(stateId) {
            return reservations.reduce((acc, cur) => (cur.state_id === stateId ? ++acc : acc), 0);
        }
    },
},

推荐阅读