简体   繁体   English

如何在vuex的actions.js中使用路由器?

[英]How to use router in actions.js of vuex?

This is code from main.js where I`ve configured my router 这是来自main.js的代码,我在其中配置了路由器

enter code here
const router = new Router({
    routes,
    mode: 'history',
    saveScrollPosition: true
});


sync(store, router);

const app = new Vue({
    router,
    store,
    render: h => h(App )
}).$mount('#app');

Then in vuex/actions.js I`ve action registerUser where I do request to API and if response is success I want to redirect user to main page 然后在vuex / actions.js中,我有一个动作registerUser,我向API请求,如果响应成功,我想将用户重定向到主页。

enter code here

export const registerUser = ({commit, state}, userData) => {
    commit(types.REQUEST_USER_REGISTER);

    api.register(userData).then(success => {
        const response = success.data;

        localStorage.setItem('id_token', response.token);

        commit(types.USER_OBJECT, response.user)

        //TODO: find better solution, then put router instance into window var
        window.router.replace('/');

    }, failure => {

    })
}

This code above works well, because I`ve set router instance into window var in build.js, maybe somebody know better solution instead of it 上面的代码很好用,因为我已经将路由器实例设置为build.js的window var,也许有人知道更好的解决方案而不是它

Move router declaration to separate file and export it. 将路由器声明移至单独的文件并导出。 Then import in main file and any other file which you wish to use it. 然后导入主文件以及您要使用的任何其他文件。 The api is the same as for $router property on vue prototype. 该API与vue原型上的$router属性相同。

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

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