【问题标题】:How can I seperate functions which are basically the same but use different states? Vue2/Vuex如何分离基本相同但使用不同状态的功能? Vue2/Vuex
【发布时间】:2021-08-06 13:25:12
【问题描述】:

我遇到了一个问题,因为我意识到我违反了 DRY(不要重复自己)规则。所以基本上我有 2 个模块(电影、电影院)和其中一些看起来相同但使用它们模块状态的方法。 示例:电影具有“电影”状态。电影院有“电影院”状态。

      //cinemas.ts
    @Mutation
  deleteCinemaFromStore(id: string): void {
    const cinemaIndex = this.cinemas.findIndex((item) => item.id === id);
    if (cinemaIndex >= 0) {
      const cinemasCopy = this.cinemas.map((obj) => {
        return { ...obj };
      });
      cinemasCopy.splice(cinemaIndex, 1);
      this.cinemas = cinemasCopy;
    } else {
      throw new Error("Provided id doesn't exist");
    }
  }

   //movies.ts
@Mutation
  deleteMovieFromStore(id: string): void {
    const movieIndex = this.movies.findIndex((item) => item.id === id);
    if (movieIndex >= 0) {
      const moviesCopy = this.movies.map((obj) => {
        return { ...obj };
      });
      moviesCopy.splice(movieIndex, 1);
      this.movies = moviesCopy;
    } else {
      throw new Error("Provided id doesn't exist");
    }
  }

我的难题是:如果这些方法引用了 2 个不同的状态,我该如何将它们分离到 utils.ts 中?

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    定义另一个以 id、状态和存储上下文 (this) 作为参数的函数:

    function delete(id:string,itemsName:string,self:any){
    
     const itemIndex= self[itemsName].findIndex((item) => item.id === id);
        if (itemIndex>= 0) {
          const itemsCopy = self[itemsName].map((obj) => {
            return { ...obj };
          });
         itemsCopy.splice(itemIndex, 1);
          self[itemsName] = itemsCopy;
        } else {
          throw new Error("Provided id doesn't exist");
        }
    }
    

    然后像这样使用它:

         //cities.ts
        @Mutation
      deleteCityFromStore(id: string): void {
       delete(id,'cities',this)
      }
    
      //countries.ts
    @Mutation
      deleteCountryFromStore(id: string): void {
        delete(id,'countries',this)
    }
    
    

    【讨论】:

    • 可以了,非常感谢!!您是否有任何文档可以阅读以扩展我的知识?我找不到任何说实话
    • 这是一个 js 的东西,它是一种很好的做法,你可以在 dev.to 等论坛上找到它们,或者你可以通过经验学习它们
    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2020-04-29
    • 1970-01-01
    • 2015-10-22
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多