【问题标题】:Undefined data when using vuex and vue-router使用 vuex 和 vue-router 时未定义的数据
【发布时间】:2019-02-03 17:08:42
【问题描述】:

我的应用程序中数据的初始状态存在问题。我正在使用 vuex 和 vue-router,我认为异步的东西让我很困惑,但我不知道如何解决它。

在我的 view.vue 组件中:

beforeRouteEnter(to, from, next) {
  store.dispatch('assignments/getAssignment', {
    id: to.params.id
  }).then(res => next());
},

在我的模块中:

getAssignment({commit, state}, {id}) {
    return axios.get('/assignments/' + id)
            .then(response => {
                if(response.data.data.type == 'goal_plan') {
                    const normalizedEntity = normalize(response.data.data, assignment_schema);
                    commit('goals/setGoals', {goals: normalizedEntity.entities.goals}, {root: true});
                    commit('goals/setGoalStrategicPriorities', {goal_priorities: normalizedEntity.entities.strategicPriorities}, {root: true});
                    commit('goals/setObjectives', {objectives: normalizedEntity.entities.objectives}, {root: true});
                    commit('goals/setStrategies', {strategies: normalizedEntity.entities.strategies}, {root: true});
                }
                commit('setAssignment', {assignment: response.data.data});
            }).catch(error => {
                console.log(error);
                EventBus.$emit('error-thrown', error);
            });
},

几个子组件下来,我想访问 state.goals.goals,但它最初是未定义的。我可以处理其中的一些问题,但不是全部。

例如,我有一个 view.vue 的子组件,其中包含

computed: {
    originalGoal() {
      return this.$store.getters['goals/goalById'](this.goalId);
    },
  },
  data() {
    return {
      form: {
        id: this.originalGoal.id,
        description: this.originalGoal.description,
        progress_type: this.originalGoal.progress_type,
        progress_values: {
          to_reach: this.originalGoal.progress_values.to_reach,
          achieved: this.originalGoal.progress_values.achieved,
        },
        due_at: moment(this.originalGoal.due_at).toDate(),
        status: this.originalGoal.status,
      },

在我开始使用 vuex 之前的那些令人兴奋的日子里,我将最初的目标作为道具传递,所以这不是问题。由于它现在已从状态中拉出,因此我收到一堆错误,它无法找到未定义的各种属性。最终 originalGoal 在显示中解析,但它永远不会以这种方式显示在表单中。

我尝试“观察”计算的道具,但我从来没有看到它何时发生变化,而且我很确定这不是正确的做法。

那么,有没有办法获取最初的数据集呢?如果没有,一旦设置了数据,我应该如何设置表单值? (欢迎任何其他建议,因为我对 vuex 和 vue-router 还很陌生。)

【问题讨论】:

  • 我认为这是因为您试图在 data() 中获取 originalGoal。为什么不直接访问表单中的计算。例如,
  • 您似乎正在实施explicit promise construction anti-pattern。不要那样做
  • 为了扩展 Phils 的评论,axios.get 返回一个 Promise,所以你不需要将它包装在另一个 Promise 中。你可以直接return axios.get()...
  • 谢谢!我已经更新以删除显式的承诺构造并返回 axios.get()。感谢您的建议!

标签: vue.js promise undefined vuex vue-router


【解决方案1】:

所以如果我在“mounted”中设置表单值,我就能让它工作。我猜仍然在学习 vue 生命周期。 :)

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 2017-07-25
    • 2023-03-06
    • 2021-07-25
    • 2020-07-22
    • 2020-01-11
    • 2020-02-24
    • 2017-12-18
    • 2016-08-10
    相关资源
    最近更新 更多