vuejs2 - 在 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 }}
我没有得到任何结果,不过我没有收到错误,请对我做错的事情有任何想法
多谢
解决方案
您可以像在 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)
})
});
}
推荐阅读
- java - 我们可以使用 Bouncy Castle 动态存储和使用这 5 个 CRT 文件吗
- php - 当请求来自外部 API 时,无法访问 Laravel 中的 cookie
- api - 谷歌安全浏览 API 不返回威胁 URL
- linux - SQLCipher:QT中使用sqlcipher的问题
- javascript - 如何基于clientX mousemove制作一个div scrollLeft
- c# - 忽略 AutoMapper 中的基本属性
- html - 如何使这个 CSS 树居中?
- c++ - 在内联函数的定义中使用 constexpr 变量时可能的 ODR 违规(在 C++14 中)
- list - 内存泄漏与 swiftUI 列表和 Firebase 数据库观察 childAdded
- python - 确定两条线位置的有效方法