【发布时间】:2020-03-18 01:53:14
【问题描述】:
我真的很难解决这个问题。尝试使用 vuex 进行分页。但是当我更改参数值时,我无法更新操作。
例如转到下一页,我尝试了一个简单的方法
在组件中:home
<button @click="nextPage()">{{currentPage}}</button>
我将参数发送到操作。
mounted(){
this.$store.dispatch('bridalApi', {currentPage})
},
data(){
return {
currentPage: 1,
};
},
methods: {
nextPage(){
this.currentPage++
}
},
在 store.js
中我接受我提出的论点。
actions: {
bridalApi({commit}, currentPage){
axios.get("api/bridal?page=" + currentPage)
.then(response => {
commit("setBridals", response.data);
})
.catch(e => {
console.log(e);
})
},
}
很明显,我无法更新 actions 中的参数。因为当我单击按钮时,它不会转到下一页。我的意思是 currentPage 里面的动作没有更新。这是第一种方式。所以,我尝试了不同的方法来解决这个问题,如下所示。
在组件中:home
<button @click="nextPage()">{{pager}}</button>
我设置/获取当前页面,并更改状态。
methods: {
nextPage(){
this.pager++
}
},
computed: {
...mapGetters([
"getBridals",
]),
pager: {
set(val){
this.$store.commit("setPagination", val);
},
get(){
return this.$store.state.bridal.pagination.currentPage;
}
},
bridals() {
return this.getBridals;
},
},
在 Store.js
中state: {
bridals: [],
pagination: {
currentPage: 1,
},
},
mutations: {
setBridals(state, bridal){
state.bridals = bridal;
},
setPagination(state, pager){
state.pagination.currentPage = pager;
},
},
getters: {
getBridals(state){
return state.bridals
},
},
actions: {
bridalApi({commit,state}){
console.log(state.pagination.currentPage)
axios.get("api/bridal?page=" + state.pagination.currentPage)
.then(response => {
commit("setBridals", response.data);
})
.catch(e => {
console.log(e);
})
},
}
但是这种方式也行不通。而且我非常没有想法。如何更新操作?使用vuex进行分页的正确方法是什么?...
【问题讨论】:
-
我猜您的第一种方法中缺少的链接是您没有以连续的方式提交分页更改。根据您提供的代码,您在
mounted事件上提交 currentPage 一次,但不再提交。您应该通过观察者观察currentPage变量(并像在mounted函数中所做的那样提交对它的更改)或调整您的 nextPage() 函数,以便它在每次点击时提交对您的商店的更改。跨度>