我想通过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
是基于数据的,思路上有些不同,上面的代码虽然能够实现功能,但总感觉不是很专业,请问有没有更好的方案实现没有更多数据
?
getList 方法写在 page.vue 里,vuex 只拿来存储公共状态。在 page.vue 里通过 commit 来改变 vuex 里的状态