创建一个我可以在突变内使用的函数

时间:2019-06-07 07:06:52

标签: javascript vue.js vuex

我正在为一个餐厅应用程序培训我的项目,该应用程序允许用户在地图上添加餐厅,添加评论...

我坚持这一点:计算评论的平均评分,并将其用于变异中,该变异用作过滤器,以仅显示地图上可见的餐厅以及用户选择的得分(星级)。

我无法从变异中访问getter,也无法从通用函数中访问状态。我已经尝试过将getter getRestaurantAvgRating函数“复制”为一个函数,但无法访问restaurantList。

我正在使用Vue-CLI和Vuex。这是商店的代码。

import Vue from 'vue';
import Vuex from 'vuex';

import restaurantFactory from '../interfaces/restaurantFactory';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    restaurantList: [],
    visibleRestaurant: [],
    sortValue: [],
    boundsValue: {}
  },
  getters: {
    getRestaurantById: (state) => {
      return (id) => {
        const restaurantIndex = getRestaurantIndex(state.restaurantList, id);
        console.log({id, restaurantIndex});
        // return state.restaurantList[id-1];
        return state.restaurantList[restaurantIndex];
      };
    },
    getRestaurantList: state => {
      return state.visibleRestaurant;
    },
    getSortValue: (state) => {
      return state.sortValue;
    },
    getBoundsValue: (state) => {
      return state.boundsValue;
    },
    getRestaurantAvgRating: (state) => {
      return (id) => {
        const restaurantIndex = getRestaurantIndex(state.restaurantList, id);
        // console.log(restaurantIndex)
        const { ratings } = state.restaurantList[restaurantIndex];

        const avgRating = ratings.reduce((acc, rating) => {
          return acc + (rating.stars / ratings.length);
        }, 0);
        return Math.round(avgRating);
      };
    }
  },
  mutations: {
    setRestaurantList: (state, { list }) => {
      state.restaurantList = list;
    },
    selectVisibleRestaurant(state) {
      const bounds = state.boundsValue;
      const range = state.sortValue;
      state.visibleRestaurant = state.restaurantList.filter((restaurant) => {
        let shouldBeVisible = true;
        let isInMap = true;
        let isInRange = true;

       if (bounds) {
         isInMap = restaurant.long >= bounds.ga.j && restaurant.long <= bounds.ga.l && restaurant.lat >= bounds.na.j && restaurant.lat <= bounds.na.l;
         shouldBeVisible = shouldBeVisible && isInMap;
       }

        if (range && range.length === 2) {
          isInRange = restaurant.ratings[0].stars >= range[0] && restaurant.ratings[1].stars <= range[1];
          shouldBeVisible = shouldBeVisible && isInRange;
        }

       console.log(restaurant.restaurantName, {
         shouldBeVisible, isInMap, isInRange, avg: restaurant.ratings[0]
       });
        return shouldBeVisible;
      });
    },
    setBoundsValue: (state, bounds) => {
      state.boundsValue = bounds;
    },
    setSortValue: (state, range) => {
      state.sortValue = range;
    },
    addRestaurant: (state, { newRestaurant }) => {
      console.log('store', { ...newRestaurant })

      const restaurantToAdd = { ...newRestaurant, ratings: [], ID: getLastId()}

      state.restaurantList.push(restaurantToAdd)
      state.visibleRestaurant.push(restaurantToAdd)

      function getLastId () {
        const lastId = state.restaurantList.reduce((acc, restaurant) => {
          if (acc < restaurant.ID) {
            return restaurant.ID
          }
          return acc
        }, 0)

        return lastId + 1
      }
    },
    addComment: (state, { restaurantId, comment }) => {
      const restaurantIndex = getRestaurantIndex(state.restaurantList, restaurantId);

      state.restaurantList[restaurantIndex].ratings.push({ ...comment })
    }
  },
  actions: {
    getData: async function (context) {
      restaurantFactory.getRestaurantList()
        .then((restaurantList) => {
          context.commit('setRestaurantList', {
            list: restaurantList
          });
          return true;
        }, (err) => {
          console.log(err);
          return false;
        });
    }
  }
});

function getRestaurantIndex (restaurantList, id) { 
  return restaurantList
    .findIndex((restaurant) => restaurant.ID === parseInt(id))
}

如果有人可以向我解释如何实现这一目标,那么获得一个可以计算平均评分并可以在“ selectVisibleRestaurant”变体中访问的函数,那就太好了!

if (range && range.length === 2) {
          // const avgRating = this.getRestaurantAvgRating();
          const avgRating = calculateAverageRating(state.restaurantList);
          console.log(avgRating);
          isInRange = restaurant.ratings[0].stars >= range[0] && restaurant.ratings[1].stars <= range[1];
          shouldBeVisible = shouldBeVisible && isInRange;
        }

我需要restaurant.ratings [0] .stars和restaurant.ratings [1] .stars来作为平均评分。

谢谢。

0 个答案:

没有答案