【问题标题】:How to set and use router in Vuex with Nuxt.js如何使用 Nuxt.js 在 Vuex 中设置和使用路由器
【发布时间】:2020-03-10 07:15:30
【问题描述】:

我到处搜索,但找不到与我的用例匹配的解决方案。我想根据输入到地址栏中的信息使用动态 URL 进行 API 调用。

我正在做一个动作:

export const actions = {
  loadAPIData({ commit }) {
    Axios.get(
      "apiUrl.com" +
        this.router.push({
          city: this.router.params.city,
          company: this.router.params.company,
          dealSlug: this.router.params.dealSlug
        }) +
        "/" +
        this.router.params.company +
        "/" +
        this.router.params.dealSlug +
        "/"
    )
      .then(r => r.data)
      .then(dealDetails => {
        commit("SET_API_DATA", dealDetails);
      });
  }
};

SET_API_DATA 提交:

export const mutations = {
  SET_API_DATA(state, dealDetails) {
    state.dealDetails = dealDetails;
    for (
      let persons = 2;
      persons <= state.dealDetails.max_vouchers_per_person;
      persons++
    ) {
      state.amountOfPeopleArr.push({
        value: persons,
        text: persons + " personen"
      });
    }
  }
}; 

然后我想从与键入的 url 匹配的 API 中获取数据,例如:apiUrl.com/Amsterdam/Pizza/get-a-pizza-for-5-dollar。

如何使用 Nuxt 将路由器导入 Vuex,如何实现我想要的行为?

【问题讨论】:

    标签: vue.js action vuex router nuxt.js


    【解决方案1】:

    首先,您需要检查您的文件夹结构是否已正确设置为具有该数量的参数。查看文档 => https://nuxtjs.org/guide/routing

    接下来,您可以将路由参数作为参数传递给您的调度方法:

      asyncData({ store, params }) {
        store.dispatch('loadAPIData', {
          city: params.city,
          company: params.company,
          dealSlug: params.dealSlug
        })
      },
    

    然后在您的商店中获取第二个参数中的有效负载:

    export const actions = {
      loadAPIData({ commit }, {city, company, dealSlug}) {
        ...
      }
    }
    

    您可以在此处阅读有关 Vuex 有效负载的更多信息 => https://vuex.vuejs.org/guide/actions.html#dispatching-actions

    【讨论】:

    • 这解决了我的问题!非常感谢你的伙伴!
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2021-12-16
    • 2016-07-17
    • 2017-10-22
    • 2014-08-28
    • 1970-01-01
    • 2017-04-05
    相关资源
    最近更新 更多