简体   繁体   中英

Vuejs + SSR + router.push() in asyncData

I got a VUEJS SSR setup, and can't figure out how to solve this.

My route is like this:

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

Then in the asyncData function I have this code:

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.

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.

My question is, can I set the updated url in my window. INITIAL_STATE ? Or can I somehow change the URL from the browser?

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 .

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' })
        })
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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