嗨,我正在努力让它在用户打开页面时不会打开,直到成功检索到来自服务器的数据,这样它在用户输入后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参数来获得主题/black/post 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();
}
感谢
您需要在beforeRouteEnter
中移动getThread
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
,则需要添加一个突变并从promise的回调中调用它。
store.commit('ADD_THREAD', response.data)