首页 > 解决方案 > 在 vuex 商店中通过 axios 获取单条记录

问题描述

我想使用 Nuxt 中的 Vuex 存储模块从后端返回一条记录。

我的组件中有以下内容,它传递了我想要的值(即 $route.params.caseId )

created () {
  this.$store.dispatch('cases/getCase', $route.params.caseId );
},

我将 $route.params.caseId 传递到我的 vuex 商店模块中的 getCase 操作中,如下所示

getCase ({ commit, context }, data) {
  return axios.get('http' + data + '.json')
  .then(res => {
    const convertcase = []
    for (const key in res.data) {
      convertcase.push({ ...res.data[key], id: key })
    }
    //console.log(res.data) returns my record from firebase (doesnt display the key though in the array, just the fields within the firebase record, but assume this is expected?

    commit('GET_CASE', convertcase)
  })
  .catch(e => context.error(e));
},

转换案例是从 firebase 键中提取 id 并将其作为 id 字段添加到我的数组中(这对于以这种方式来自 firebase 的单个结果是否正确?)

我的突变

// Get Investigation
GET_CASE(state, caseId) {
  state.caseId = caseId;
},

现在当我使用

案例名称:{{ caseId.case_name }}

我没有得到任何结果,

不过我没有收到错误,请对我做错的事情有任何想法

多谢

标签: vuejs2vuexnuxt.jsvuex-modules

解决方案


您可以像在 dispatch 方法中那样将更多数据传递给操作,然后正常访问它们。

请注意 getCase 函数的 data 参数,在您的示例中 data === $route.params.caseId

//加载单查

getCase ({ commit, context }, data) {
  return axios.get('http' + investigationID + '.json')
  .then(res => {
    const convertcase = []
    for (const key in res.data) {
      convertcase.push({ ...res.data[key], id: key })
    }
    commit('GET_CASE', convertcase)
  })
  .catch(e => context.error(e));
},

如果您想使用 Promise,请查看下面我的应用程序中获取单个 BLOG_POST 的操作的示例

let FETCH_BLOG_POST = ({commit, state}, { slug }) => {

    return new Promise((resolve, reject) => {

        fetchBlogPost(slug, state.axios)
        .then((post) => {
            console.log("FETCH_BLOG_POSTS", post.data.data)
            commit('SET_BLOG_POST', post.data.data)
            resolve(post.data)
        })
        .catch((error) => {
            console.log("FETCH_BLOG_POST.catch")
            reject(error)
        })

    });
}

推荐阅读