首页 文章

使用vuex和vue-router时未定义的数据

提问于
浏览
0

我的应用程序中的初始数据状态存在问题 . 我正在使用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之前的令人兴奋的日子里,我作为道具传递了最初的目标,所以这不是问题 . 由于它现在从状态中拉出来,我得到了一堆错误,它找不到undefined的各种属性 . 最终originalGoal在显示中解析,但它永远不会以这种方式显示在表单中 .

我试着“观察”计算出的道具,但我从未看到它何时发生变化,而且我很确定无论如何都不是正确的方法 .

那么,有没有办法最初获取数据集?如果没有,一旦设置数据,我该如何设置表格值? (欢迎任何其他建议,因为我对vuex和vue-router很新 . )

1 回答

  • 0

    因此,如果我在“已安装”中设置表单值,我可以使其工作 . 我还在学习关于vue生命周期的知识 . :)

相关问题