今天学Vuex遇到的两个小坑

  • 写影院搜索页面 , 忘记判断mounted中的影院数据cinemasList是请求得到 , 还是利用缓存的 , 导致我 mounted中的this.$store.state.cinemasList , 刷新搜索页面以后一直是空数组 (缓存被清空了 , 数据自然冒得咯) , 应该有个判断 :
// 防止刷新以后数据请求为空 , 因为不确定用户先进的search 还是 cinema页面
    if (this.$store.state.cinemasList.length === 0) {
      this.$store.dispatch('getCinemasAction')
    } else {
      console.log('使用缓存')
    }
  }
  • 影院页面要显示前五个离我最近的推荐影院 , 利用计算属性
 computed: {
    // 取前五条数据 , 
    //注意:不能用splice , 会影响原数组cinemasList , 然后又引起计算属性变化 , 死循环
    cinemasContent () {
      return this.$store.state.cinemasList.slice(0, 5)
    }
  }

开始用的splice方法取前五条数据 , 报错Unexpected side effect in "cinemasContent" computed property

原因如下 :

splice有”裁剪”作用 , 会影响原数组cinemasList , cinemasList改变又引起cinemasContent重新计算 , 又影响了cinemasList , 死循环 .

所以用slice , 不影响原数组

( ps: 暂时没学到getters , 所以用的computed )

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理