简体   繁体   English

asyncData 中的 Vuejs + SSR + router.push()

[英]Vuejs + SSR + router.push() in asyncData

I got a VUEJS SSR setup, and can't figure out how to solve this.我有一个 VUEJS SSR 设置,但不知道如何解决这个问题。

My route is like this:我的路线是这样的:

{
  path: '/:blogSlug', component: BlogPost, name: 'blog-post'
}

Then in the asyncData function I have this code:然后在 asyncData 函数中我有这个代码:

asyncData({store, route, router}) {
            let slug = route.params.blogSlug

            if (!store.state.blog.posts[slug]) {
                return store.dispatch('FETCH_BLOG_POST', { slug: slug }).catch((error) => {
                    console.log("error - pushing to /404")
                    router.push('/404');
                })
            }

            return(Promise.resolve());
        }

This works now if I disable my javascript, mainly because on the server asyncData() is executed, then if the blog post is not found I push ('/404') which displays a pretty "Not found" page and html is sent back to browser.如果我禁用我的 javascript,这现在有效,主要是因为在服务器上执行了 asyncData(),然后如果没有找到博客文章,我推送 ('/404') 它显示一个漂亮的“未找到”页面并且 html 被发回到浏览器。

Then, mainly because the URL in the browser has NOT changed, during the hydration process everything blows because VueJS is still trying to render the BlogPost component instead of the 404.然后,主要是因为浏览器中的 URL 没有改变,在 hydration 过程中一切都失败了,因为 VueJS 仍在尝试渲染 BlogPost 组件而不是 404。

My question is, can I set the updated url in my window.我的问题是,我可以在我的窗口中设置更新的 url。 INITIAL_STATE ?初始状态 Or can I somehow change the URL from the browser?或者我可以以某种方式从浏览器更改 URL?

I can add everything you need to the question if it's not clear.如果不清楚,我可以将您需要的所有内容添加到问题中。

Well, I figured it out and didn't update.嗯,我弄明白了,没有更新。 Might as well do it now better than never.不妨现在就做总比不做要好。

Nuxt also provides an error function as a parameter in asyncData . Nuxt 还提供了一个error函数作为asyncData的参数。

This is solved the following way:这是通过以下方式解决的:

asyncData({store, route, router, error}) {
    let slug = route.params.blogSlug

    if (!store.state.blog.posts[slug]) {
        return store.dispatch('FETCH_BLOG_POST', { slug: slug }).catch((error) => {
            console.log("error - pushing to /404")
            error({ statusCode: 404, message: 'Post not found' })
        })
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM