【发布时间】:2021-10-08 17:29:47
【问题描述】:
在 History 视图中,我通过调用 created() 中的 Vuex 操作从后端服务器下拉历史记录,并使用访问历史模块状态的计算函数 history() 将数据传递到历史记录表。
问题是,每次我返回 History 视图时,由于调用 created() 中的操作,会向服务器发出一个新请求。
如何设置以便在第一次访问视图时进行调用,并依赖历史状态来后续访问此视图?
History.vue
<script>
import { mapActions } from "vuex";
export default {
name: "History",
data() {
return {
// data
};
},
methods: {
...mapActions(["fetchHistory"]),
refresh() {
this.fetchHistory()
},
computed: {
history() {
return this.$store.state.history.records;
},
},
created() {
this.refresh();
},
};
</script>
historyModule.js
async fetchHistory({commit}){
await axios.get('api/history')
.then((response) => {
commit('setHistory', response.data)
return Promise.resolve();
})
.catch((error) => {
commit('setHistory', [])
return Promise.reject(error)
})
}
【问题讨论】: