First, we will implement the logout action.
- Let's add a logout action in the posts Vuex module that clears the posts fetching data:
logout ({ commit }) {
commit('posts', {
posts: [],
mapBounds: null,
})
},
- We can call this from the logout action in the main store (in the store/index.js file):
logout ({ commit, dispatch }) {
commit('user', null)
$fetch('logout')
// ...
dispatch('posts/logout')
},
This is going to work, but we can improve this code--we could define the logout action of the posts namespaced submodule as a root action. That way, when we dispatch the 'logout' action, both the logout and the posts/logout will be called!
- Use this object notation in the posts module for the logout action:
logout: {
handler ({ commit }) {
commit('posts', {
posts: [],
mapBounds: null,
})
},
root: true,
},
The handler property is the function called on this action, and the root60;Boolean property indicates if this is a root action. Now the logout action is no longer namespaced regarding the action dispatching system, and will be called if a non-namespaced 'logout' action is dispatched.
The state, getters, commit, and dispatch made inside this logout action are still namespaced to the module. Only its invocation is no longer namespaced!
- You can remove the dispatch('posts/logout') line from the logout action on the main store.