我正在构建具有vuex支持的nuxtjs
应用程序,我在一个应用程序页面中添加了fetch hook,当我第一次加载该应用程序时,它会触发分派vuex动作并更改整数状态的钩子变量,但是当我刷新页面或转到其他页面时,所有状态变量都返回其初始值。
页面代码:pages/components.vue
<template>
<div>
<h1>Total {{ total }}</h1>
<h3>Number 1 {{ number_one }}</h3>
<h3>Number 2 {{ number_two }}</h3>
<h3>Number 3 {{ number_three }}</h3>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: "components",
head() {
return {
title: 'Components Page'
}
},
async fetch({ store, error }) {
try {
await store.dispatch('cdata/fetchData');
} catch (e) {
error({
statusCode: 503,
message: 'Unable to fetch data at this time, please try again later.'
});
}
},
computed: {
...mapState({
total: state => state.cdata.total,
number_one: state => state.cdata.number_one,
number_two: state => state.cdata.number_two,
number_three: state => state.cdata.number_three,
}),
}
}
</script>
vuex存储模块:store/cdata.js
import ComponentService from '~/services/Covid19Service.js';
export const state = () => ({
total: 0,
number_one: 0,
number_two: 0,
number_three: 0
});
export const mutations = {
SET_COMPONENTS_DATA(state, payload){
state.total = payload.total;
state.number_one = payload.number_one;
state.number_two = payload.number_two;
state.number_three = payload.number_three;
}
}
export const actions = {
fetchData({ commit }){
ComponentService.getData().then(response => {
commit('SET_COMPONENTS_DATA', response.data);
});
}
}
ComponentService是axios服务:services/ComponentService.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: `/api`,
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
export default {
getData() {
return apiClient.get('/cdata');
}
}
我在哪一部分出错了,请指教