【问题标题】:How to use RESTful API with Vuex and Axios for Dashboard如何将 RESTful API 与 Vuex 和 Axios 一起用于 Dashboard
【发布时间】:2018-12-31 09:33:21
【问题描述】:

我是 Vuex 和 REST API 的新手,但需要使用 Vuex 和 Axios 将仪表板连接到后端 REST API 并且遇到了一些麻烦。

例如,我需要将一个参与者添加到我们的参与者数组中,这是我们在 Vuex 存储中的状态之一。我在这里开始了一些操作,例如“加载参与者”,它连接到我们的后端并加载所有参与者数据。和“添加参与者”应该添加参与者。

我对流程以及如何将仪表板中的实时信息也连接到此感到困惑。在我们的仪表板上,我们有一个“新参与者”表格,您可以在上面输入姓名、电子邮件、性别等。如何将提交的数据输入到我的新参与者对象中?

这是一个动作的sn-p:

actions: {
async loadParticipants ({commit}) {
  try {
    await axios
      .get('/dash/participants')
      .then(r => r.data)
      .then(participants => {
        commit('setParticipants', participants)
      })
  }

  catch (e) {
    if (e.response)
      commit('Error?')

    throw e
  }
},


async getFilteredParticipants ({ state, commit, getters}) {
  try {
    const {data: participants} = await axios.get('dash/participants')
    commit('filterParticipants', participants, getters)
  }
  catch (e) {
    if (e.response)
      commit('Error?')

    throw e
  }

  }
},

async addParticipant ({ state, commit})
{
  //Need to get this data from New Participant modal?
  const participant = {
    name: 'Amy',
    email: 'amy@gmail.com',
    sex: 'female',
    tags: ['dog', 'cat'],
    createdBy: null,
    updatedBy: null,
    pendingEvalSentDate: Date,
    pendingEvalViewedEmailDate: Date,
    pendingEvalClickedLinkDate: Date,
    completedEvalHistorySummary: null
  }

  try {
    await axios
      .post('/dash/participants')
      commit('addParticipants', participant)
  }
  catch (e) {
    if (e.response)
      commit('Error?')

    throw e
  }
},

【问题讨论】:

    标签: rest vue.js axios vuex dashboard


    【解决方案1】:

    在您的模板中: <form action="" v-on:submit.prevent="submitParticipant">

    然后,您必须在“新参与者”组件中创建一个提交方法,例如:

    submitParticipant() {
       this.$store.dispatch('addParticipant', this.participant);
    }
    

    或:

    submitParticipant() {
       this.$store.dispatch('participantModule/addParticipant', this.participant);
    }
    

    如果您的商店分为模块,addParticipant 保存在participantModule 中。

    考虑到您将当前编辑的参与者保留在组件的数据中:

    data() {
       return {
          participant: {} 
       }
    }
    

    那么您在商店中的 addParticipant 操作将如下所示:

    addParticipant({ commit }, participant) {
       axios.post('/dash/participants', participant)
            .then(response => {
               console.log(response);
               commit('addParticipants', participant)
             })
            .catch(error => console.log(error));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2020-06-22
      • 2018-02-22
      • 2021-04-08
      • 2022-12-01
      • 2014-02-05
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      相关资源
      最近更新 更多