vuejs / vuex-router-sync

Effortlessly keep vue-router and vuex store in sync.
MIT License
2.52k stars 125 forks source link

通过提交'route/ROUTE_CHANGED'的mutation来实现路由跳转是否合理? #92

Closed Jim-Rae closed 5 years ago

Jim-Rae commented 5 years ago

您好!

我的需求是这样的。我在vuex的action里fetch用户数据,如果未登录则跳转到登录页。 我以前的做法是在main.js里把创建的vue实例赋值到window.vue里,然后在store.js里通过vue.$router操作路由。

可是我觉得这种方法应该不是最优解,我上网查阅到使用vuex-router-sync可以通过提交'route/ROUTE_CHANGED'的mutation来实现路由跳转 commit('route/ROUTE_CHANGED',{to: {name : 'routeName'}})

不过我看到您的说明文档里提到store.state.route是不可更改的 image

而且您的文档里也没有提到通过提交'route/ROUTE_CHANGED'的mutation来实现路由跳转这一方法,所以我想问一下您,这方法合理吗?您是否推荐这样用呢?

如果不能像双向绑定那样通过修改store.state.route实现路由跳转的话,那vuex-router-sync不是仅仅只能在vuex里获取路由信息而已吗?

posva commented 5 years ago

It's better not to do routing like that. You can import the router instance anywhere in your Vuex code to trigger navigation by calling router.push and others

Jim-Rae commented 5 years ago

@posva Do you mean that I can trigger navigation like that ?

// router.js
import router from './router'

export default new Vuex.Store({
  //...
  actions: {
    //...
    // actions to update route asynchronously
    routerPush (_, arg) {
      router.push(arg)
    },
    routerGo (_, arg) {
      router.go(arg)
    }
  }
})

I can also get the route object by calling router.currentRoute, if I use this mode to trigger navigation by calling router.push. So what are the benefits of using vuex-router-sync?