使用vuex实现上拉加载更多功能的问题

我想通过vuex来实现上拉加载更多时没有更多数据的提示,但不知数据处理应该怎么写,目前获取数据是用下面的代码实现的

store/moduleA.js:

const state = {
  lists:[],
  nomore:false    //是否有数据
};

const mutations = {
  GetList(state,res) {    
    state.lists = state.lists.concat(res);
  }
  NoMore(state,res) {
    state.nomore = res;
  }
};

const actions = {
  async getList({commit},page) {
    await axios.get("url?p="+page).then(function (response) {
      let res = response.data;    //如果获取不到更多数据,应该怎么处理才能通知到vue组件?
      
      if(res.length > 0) {
          commit('NoMore',false);
          commit('GetList',res);
      } else {
          commit('NoMore',true);
      }
    });
  }
};

在组件里通过dispatch获取新数据
page.vue:

data() {
    return {
        nomore:false
    }
},
watch:{
   isNoMore(val) {
       this.nomore = val;
   }
},
computed:{
    ...mapState({
        isNoMore:state => state.nomore
    })
},
this.$store.dispatch('getList',page).then(function () {
    if(this.nomore) {
        console.log('没有更多数据了')
    } else {
       //do something
    }
});

如果用普通的写法,可以通过服务器返回的信息来判断,但vue是基于数据的,思路上有些不同,上面的代码虽然能够实现功能,但总感觉不是很专业,请问有没有更好的方案实现没有更多数据

阅读 2.7k
2 个回答

getList 方法写在 page.vue 里,vuex 只拿来存储公共状态。在 page.vue 里通过 commit 来改变 vuex 里的状态

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进