【问题标题】:access state data from store into a string vue.js将状态数据从 store 访问到字符串 vue.js
【发布时间】:2018-08-01 19:58:29
【问题描述】:

大家好,我正在尝试将我的商店中的状态数据添加到我在操作中的一个 axios 调用中的字符串中。这是我的商店:

export const store = new Vuex.Store
({
  state: {
    participants: [],
    filterTags: ["foo", "swag"],
    page: 1,
    perPage: 2,
    filterTagName: "",
   }
}

这是我的行动呼吁:

 actions: {
async loadParticipants ({commit}) {
  try {
    console.log(this.state.page);
    await axios
  .get('/dash/participant?perPage=2&page=1&string=f')

      .then(r => r.data)
      .then(participants => {
        console.log(participants.docs);
        console.log("Hit me");
        commit('setParticipants', participants)
      })
  }
  catch (e) {
    if (e.response)
      console.log(e.response);
    throw e
  }
}

我想在 axios 调用中的 { INSERT DATA HERE } 处添加商店的状态数据:

 .get('/dash/participant?perPage={INSERT DATA HERE }&page={ INSERT DATA HERE }&string=f')

感谢您的任何意见!

【问题讨论】:

  • 这需要重新标记为 vuejs2 吗?

标签: string vue.js axios vuex


【解决方案1】:

在您的操作中,您可以访问整个商店,因此您也可以添加状态:

async loadParticipants ({commit, state}) {

因此您可以在方法主体中使用state 变量:

actions: {
  async loadParticipants ({commit, state}) {
    try {
      console.log(this.state.page);
      await axios
    .get(`/dash/participant?perPage=${state.perPage}&page=${state.page}&string=${state.filterTagName}`)

        .then(r => r.data)
        .then(participants => {
          console.log(participants.docs);
          console.log("Hit me");
          commit('setParticipants', participants)
        })
    }
    catch (e) {
      if (e.response)
        console.log(e.response);
      throw e
    }
  }
}

【讨论】:

    【解决方案2】:

    所以你只想用你的 vuex 存储中的值填充你的查询参数? 只需将state 传递给您的操作即可。然后您可以借助模板迭代将状态添加到查询参数中。 ${some-js-variable}

    您也可以直接破坏响应并获取数据。 如果您使用 asyncawait,不知道为什么要做出像 then() 这样的承诺。

    actions: {
     async loadParticipants ({commit, state}) {
      try {
        const {data} = await axios.get(`/dash/participant?perPage=${state.perPage}&page=${state.page}&string=f`)
        console.log(data)
    
      }
      catch (e) {
        if (e.response)
          console.log(e.response);
        throw e
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 2023-03-18
      • 2021-08-27
      • 2016-09-29
      • 2020-08-09
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多