Vuex + Vue 一次从服务器拉取状态

Vuex + Vue pull state from server just once

在历史视图中,我通过调用 created() 中的 Vuex 操作从后端服务器提取历史记录,并使用计算函数 history() 将数据传递给历史记录 table ] 访问历史模块状态。

问题是,每次我 return 到历史视图时,都会由于调用 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)
        })
}

如果 history.records 是数组,您可以在调度操作之前检查长度:

created() {
  if(!this.$store.state.history.records.length) this.refresh();
},

如果您希望此模式跨组件工作,您可以将相同的行为添加到 Vuex 操作而不是创建的挂钩。这也会将您所有的 Vuex 行为保留在您的商店代码中。