Using conditional class with store getters: not updating class

时间:2018-12-27 12:58:42

标签: vue.js vuejs2 vuex

I have a div with a conditional class that works well when the app is loaded, but it's not updated when the store data change.

The code in my vue component looks like this

<span class="week-day" 
    v-bind:class="{ complete: isDayComplete(day) }" 
    v-for="day in daysInWeek" 
    v-bind:data-day="day"
>&nbsp;</span>

And I have ...mapGetters(['isDayComplete']) in my computed object.

The getter looks like this

isDayComplete(state) {
  return (day) => {
    console.log(`called isDayComplete(${day})`)
    const formattedDay = moment(day, 'DD/MM/YYYY').format('YYYY-MM-DD');
    if (state.daysData[formattedDay]) {
      if (state.daysData[formattedDay].meals.length > 0) {
        console.log(`day ${day} is complete`);
        return true;
      } else {
        console.log(`day ${day} is NOT complete`);
        return false;
      }
    } else {
      console.log(`no data for day ${day}`);
      return false;
    }      
  }
},

I update my meals data in a mutation

updateMeals(state, meals) {
  _.forEach(meals, (meal) => {
    state.daysData[meal.day].meals.push(meal);
  });
}

And I have an action that commits that mutation

loadMeals({ state, commit }) {
  return new Promise((resolve, reject) => {
    get.meals.from.api()
      .then((response) => {
        commit('initDaysData');
        commit('updateMeals', response.data.data);
        return resolve();
      })
    .catch(reject);
  });
}

So whenever I call loadMeals the class is not updated if one day changes its status (complete/not-complete). If I reload the page, the class is set correctly.

What am I doing wrong? Thanks!

2 个答案:

答案 0 :(得分:1)

这是一个常见的反应性问题。您可以进行深度复制(使用JSON.parse(JSON.stringify()))以使数据具有响应性:

updateMeals(state, meals) {
  _.forEach(meals, (meal) => {
    state.daysData[meal.day].meals.push(meal);
  });
  state.daysData = JSON.parse(JSON.stringify(state.daysData))
}

答案 1 :(得分:0)

@ittus答案是正确的。我找到了另一种可能实现这一目标的方法 帮助别人。

1)在商店中添加另一个mutation

updateCompletedDays(state) {
  const newState = [];
  _.forEach(state.daysData, (currentDayData, currentDay) => {
    if (currentDayData.meals.length > 0) {
      newState.push(currentDay);
    }
  });
  state.completedDays = newState;
},

2)在进餐后进行这种突变

3)将isDayComplete吸气剂更改为

isDayComplete(state) {
   const formattedDay = moment(day, 'DD/MM/YYYY').format('YYYY-MM-DD');
   return state.completedDays.indexOf(formattedDay) !== -1;
}

基本上,当使用反应性深入数组/对象时,最好使用聚合数据数组(也请检查Vue.set API)