0

I have 2 questions. 1. How can I catch undefined routes and redirect to 404 page? 2. How I can use Vuex actions to get data from api? I know that vuex mutations must be sync and actions async. But I can get data with mutations and can use then promise. but can't in actions or I do anything mistake. Please give me beautiful example for that(component type). I use vuex in laravel mix in Laravel project. Thanks...

1 Answer 1

1

Generally speaking, you shouldn't be getting undefined routes if you're defining all of the routes within an app. You can define a redirect in your routes configuration as such:

[
    {
        path: 'admin/posts/list',
        name: 'post-list',
    },
    {
        path: 'admin/posts',
        redirect: 'admin/posts/list'
    }
]

// you can also redirect to a named route instead
// of a path like this:
{
    path: 'admin/posts',
    redirect: { name: 'post-list' }
}

If you wanted to do a "catch all" that grabs any paths not matched and redirect to your 404 component/view, then you could do it like this:

{
    path: '*',
    redirect: '/404'
}

Make sure that is at the bottom of your routes definition as the last route because it will catch any routes in the tree it is above.

As for your question about mutations/actions, asynchronous API requests like fetching data from an API only every happen within actions when you're using Vuex.Taken from the documentation on actions:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answers. ;-) How I must use it in mutations or actions? jsfiddle.net/d9j44zom
You really should read the Vuex documentation carefully. Dispatching actions is spelled out quite clearly: vuex.vuejs.org/en/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.