【问题标题】:get single record through axios in vuex store在 vuex 商店中通过 axios 获取单条记录
【发布时间】:2018-06-21 15:11:08
【问题描述】:

我想使用 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 }}

我没有得到任何结果,

虽然我没有收到错误,请对我做错了什么有任何想法

非常感谢

【问题讨论】:

    标签: vuejs2 vuex nuxt.js vuex-modules


    【解决方案1】:

    您可以像在 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)
            })
    
        });
    }
    

    【讨论】:

    • 感谢您的回复,我的问题解决了一半,但没有得到任何结果,首先尝试第一种方法,看看我是否可以让事情正常工作,请参阅对原始问题的编辑,请知道我的问题是什么
    猜你喜欢
    • 2011-12-14
    • 2018-09-13
    • 2018-11-29
    • 2019-03-23
    • 2017-02-24
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多