【问题标题】:beforeRouteEnter infinite loopbeforeRoute进入无限循环
【发布时间】:2017-09-06 08:17:48
【问题描述】:

我在使用 Vue 路由器时遇到了这个问题。

我的方案是允许首先加载 /,从那里获取一些数据,然后它将转到 /chat/:chatId 路由并在那里呈现 UI,其中 :chatId 参数是根据我从 API 获得的数据设置的.

我有 /['chat', 'chat/:chatId'] 作为路由别名。

我有这个问题的组件内保护。

beforeRouteEnter(to, from, next) {
  store.dispatch('fetchOpenSessions')
  .then(() => {
    const firstChat = Object.keys(store.state.chatsidebar.openSessions)[0];
    next({ name: 'chat', params: { chatId: firstChat } });
  });
},

但是这段代码最终会无限循环,导致浏览器挂起。

我的问题是,如果我的初始路线是//chat,我该如何设置chat/:chatId 而不会进入无限循环?

【问题讨论】:

    标签: javascript vue.js vue-router


    【解决方案1】:
    beforeRouteEnter(to, from, next) {
        store.dispatch('fetchOpenSessions')
            .then(() => {
                if(to.name == 'chat'){
                    next();
                }else{
                    const firstChat = Object.keys(store.state.chatsidebar.openSessions)[0];
                    next({ name: 'chat', params: { chatId: firstChat } });
                }
            });
    },
    

    【讨论】:

    • 哇。这就说得通了。感谢您的回答。 5分钟后我会接受! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多