【问题标题】:Vuex is resetting already set statesVuex 正在重置已设置的状态
【发布时间】:2021-01-10 23:25:03
【问题描述】:

已经开始玩 Vuex,有点困惑。

每次我加载组件company.vue时它都会触发动作GET_RECRUITERS,因此也会进行api调用。

例如,如果我打开 company.vue => 使用 vue-router 导航到 user/edit.vue,然后他们返回,它将再次调用 action/api(招聘人员根据 Vue-dev-tools 保存在商店中)。

如果我错了,请纠正我 - 如果我再次返回页面,它不应该触发操作/api 并因此重置状态,对吗?还是我误解了 Vuex 的意图?

company.vue

<template>
  <card>

    <select>
      <option v-for="recruiter in recruiters"
              :value="recruiter.id">
        {{ recruiter.name }}
      </option>
    </select>

  </card>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  middleware: 'auth',

  mounted() {
    this.$store.dispatch("company/GET_RECRUITERS")
  },

  computed: mapGetters({
    recruiters: 'company/recruiters'
  }),

}
</script>

company.js

import axios from 'axios'

// state
export const state = {
  recruiters: [],
}

// getters
export const getters = {
  recruiters: state => { 
    return state.recruiters
  }
}

// actions
export const actions = {
  GET_RECRUITERS(context) {

    axios.get("api/recruiters")
      .then((response) => {
        console.log('API Action GET_RECRUITERS')
        context.commit("GET_RECRUITERS", response.data.data) 
      })
      .catch(() => { console.log("Error........") })
  }

}

// mutations
export const mutations = {
  GET_RECRUITERS(state, data) {
    return state.recruiters = data
  }
}

谢谢!

【问题讨论】:

  • 您在 mounted 钩子中有请求,因此每次安装组件时都会调用它。改为在 created 挂钩中尝试

标签: vue.js vuex vue-router state-management


【解决方案1】:

这是预期的行为,因为除非您缓存它,否则每次您路由回它时都会再次创建/安装一个页面组件。这里有一些设计模式:

  • 将数据加载到只运行一次的App.vue中。

  • 或者,在调用 API 之前检查数据是否已经加载:

// Testing that your `recruiters` getter has no length before loading data
mounted() {
   if(!this.recruiters.length) {
      this.$store.dispatch("company/GET_RECRUITERS");
   }
}
  • 或者,缓存页面组件,以便在每次路由离开和返回时都不会重新创建它。通过使用&lt;keep-alive&gt; 组件包装&lt;router-view&gt; 来做到这一点:
<keep-alive>
   <router-view :key="$route.fullPath"></router-view>
</keep-alive>

【讨论】:

    猜你喜欢
    • 2020-11-24
    • 2018-10-19
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2019-10-12
    • 2018-07-04
    相关资源
    最近更新 更多