【问题标题】:Using vue router BeforeRouteEnter method to wait for http request to complete使用vue路由器BeforeRouteEnter方法等待http请求完成
【发布时间】:2023-03-31 15:55:01
【问题描述】:

您好,我正在尝试这样做,以便当用户打开页面时,在成功检索来自服务器的数据之前它不会打开,这样它就不会在用户输入后 0.5 秒左右出现。

为此,我读到我需要使用 BeforeRouteEnter,但我无法找到有关如何正确使用它的信息,尤其是在等待我的 REST API 完成其请求时。

这是我希望在路由到我的新组件之前等待完成的方法:

 async getThread() {
            const response = await postsService.fetchOneThread({
                id: this.blockId,
                topic: this.topicId,
                thread: this.postId
            });
            this.thread = response.data;
        }

只有 this.thread = response.data 之后,我才希望页面显示。

需要注意的重要一点是,我还通过 URL 参数来获取主题/黑色/帖子 ID 的数据。

这也是我的 getUrlParam 方法

url() {
            let x = this.$route.params.topic.split('-');
            this.topicId = x[0];

            let y = this.$route.params.id.split('-');
            this.blockId = y[0];

            let post = this.$route.params.thread.split('-');
            this.postId = post[1];

            this.getThread();
        }

谢谢

【问题讨论】:

  • 你需要在任何你想“等待”异步函数完成的地方使用await关键字。
  • ?这不是我的问题
  • 那你的问题是什么?您只需要使用awaitbeforeRouteEnter 调用getThread

标签: vue.js routes vue-router


【解决方案1】:

您需要将getThread 移动到beforeRouteEnter

beforeRouteEnter: (to, from, next) => {
  postsService.fetchOneThread({
    id: this.blockId,
    topic: this.topicId,
    thread: this.postId
  }).then( response => {
     //store the data somewhere accessible
     next()
  })
},

几点说明:

  • 我不认为beforeRouteEnter 可以是异步的,所以我使用then 来获取响应
  • 组件尚未准备好,因此您还无法访问它,您需要将信息保存在其他位置,以便组件可以读取。我建议为此使用Vuex

如果您决定使用Vuex,则需要添加一个突变并从承诺的回调中调用它。

store.commit('ADD_THREAD', response.data)

【讨论】:

  • beforeRouteEnter 可以是异步的 (example)。
猜你喜欢
  • 2020-12-09
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 2017-06-01
  • 2017-07-04
  • 2019-05-19
  • 1970-01-01
  • 2019-05-08
相关资源
最近更新 更多