使用 NuxtJS 和 Vuex 路由 404 - 组件应该调用突变还是可以操作 return 承诺?
Routing 404's with NuxtJS and Vuex - should components call mutations or can actions return promises?
我想弄清楚如何在 NuxtJS 中处理我的路由的外部验证。
假设我有一个动态加载的帖子页面
{ path: '/posts/:id?', name: 'posts-id', component: Post }
然后检查是否存在具有给定 ID 的实际 post,我需要调用我的 API 并获取 post 或处理 404.
AsyncData
通过下面的例子给了我这种可能性
export default {
asyncData ({ params, error }) {
return axios.get(`https://my-api/posts/${params.id}`)
.then((res) => {
return { title: res.data.title }
})
.catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
}
}
但是,它会在组件上设置数据,但我希望将其设置在我的 Vuex 商店中。这通过将 asyncData
更改为 fetch
并允许我直接变异和调用操作来解决。直接 mutating 是不对的,但是如果我使用 action 就无法处理 404 错误。
那么我该怎么做呢?
Afaik asyncData 和 fetch 之间的区别仅在第一个 return 数据中,而在第二个中则没有。就这样。你可以做所有其他的事情。
至于无法处理 404 - 不确定你有什么问题。但是这样的事情会起作用
export default {
fetch ({ params, error, store }) {
return axios.get(`https://my-api/posts/${params.id}`)
.then((res) => {
store.dispatch('yourAction', { title: res.data.title } )
})
.catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
}
}
我忽略了一个事实,即您可以简单地 return 从操作中获得承诺。这使我能够处理组件本身的 404 状态,同时将我的请求保留在我的商店中。
Post 页数
async fetch ({ store, params, error }) {
await store.dispatch('article/GET', params).catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
},
存储操作
async GET({commit}, params) {
return new Promise((resolve, reject) => {
axios.get('/posts/' params[0).then((res) => {
let data = res.data
commit('SET', data)
resolve()
}).catch((e) => {
reject(e)
})
})
},
我想弄清楚如何在 NuxtJS 中处理我的路由的外部验证。
假设我有一个动态加载的帖子页面
{ path: '/posts/:id?', name: 'posts-id', component: Post }
然后检查是否存在具有给定 ID 的实际 post,我需要调用我的 API 并获取 post 或处理 404.
AsyncData
通过下面的例子给了我这种可能性
export default {
asyncData ({ params, error }) {
return axios.get(`https://my-api/posts/${params.id}`)
.then((res) => {
return { title: res.data.title }
})
.catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
}
}
但是,它会在组件上设置数据,但我希望将其设置在我的 Vuex 商店中。这通过将 asyncData
更改为 fetch
并允许我直接变异和调用操作来解决。直接 mutating 是不对的,但是如果我使用 action 就无法处理 404 错误。
那么我该怎么做呢?
Afaik asyncData 和 fetch 之间的区别仅在第一个 return 数据中,而在第二个中则没有。就这样。你可以做所有其他的事情。 至于无法处理 404 - 不确定你有什么问题。但是这样的事情会起作用
export default {
fetch ({ params, error, store }) {
return axios.get(`https://my-api/posts/${params.id}`)
.then((res) => {
store.dispatch('yourAction', { title: res.data.title } )
})
.catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
}
}
我忽略了一个事实,即您可以简单地 return 从操作中获得承诺。这使我能够处理组件本身的 404 状态,同时将我的请求保留在我的商店中。
Post 页数
async fetch ({ store, params, error }) {
await store.dispatch('article/GET', params).catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
},
存储操作
async GET({commit}, params) {
return new Promise((resolve, reject) => {
axios.get('/posts/' params[0).then((res) => {
let data = res.data
commit('SET', data)
resolve()
}).catch((e) => {
reject(e)
})
})
},