vue-router beforeRouteUpdate 钩子无法访问`this` [英] vue-router beforeRouteUpdate hook can't access `this`
问题描述
我正在使用 vue-router 构建一个 Vue.js 应用程序.
I'm building a Vue.js application using vue-router.
从 doc 我可以在钩子内阅读 beforeRouteUpdate
我可以通过关键字 this
完全访问组件:
From the doc I can read that inside the hook beforeRouteUpdate
I have full access to the component through the keyword this
:
注意 beforeRouteEnter 是唯一支持传递回调到下一个.对于 beforeRouteUpdate 和 beforeRouteLeave,这是已经可用,因此不需要传递回调,因此不支持:
Note that beforeRouteEnter is the only guard that supports passing a callback to next. For beforeRouteUpdate and beforeRouteLeave, this is already available, so passing a callback is unnecessary and therefore not supported:
所以我写了下面的代码:
So I wrote the following code:
...
methods: {
...mapActions({
setFileDetails: 'setFileDetails',
setActionParams: 'setActionParams',
setSelectedFileId: 'setSelectedFileId',
}),
goToImportSource() {
this.$router.push('/import');
},
openAnnotationsView(item) {
this.$router.push(`/ingestion/queue/${item.id}`);
},
},
beforeRouteUpdate: (
to,
from,
next,
) => {
this.setSelectedFileId(to.params.id);
next();
},
};
</script>
但我收到此错误:
vue-router.esm.js?fe87:16 [vue-router] uncaught error during route navigation:
TypeError: _this.setSelectedFileId is not a function
at VueComponent.beforeRouteUpdate (PageIngestionQueue.vue?3869:67)
at boundRouteGuard (vue-router.esm.js?fe87:2080)
at iterator (vue-router.esm.js?fe87:1943)
at step (vue-router.esm.js?fe87:1717)
at step (vue-router.esm.js?fe87:1721)
at step (vue-router.esm.js?fe87:1721)
at step (vue-router.esm.js?fe87:1721)
at eval (vue-router.esm.js?fe87:1718)
at eval (vue-router.esm.js?fe87:1964)
at eval (routeRules.js?b464:9)
如果我在组件中的任何其他地方调用 this.setSelectedFileId
,它可以工作......我错过了什么?
If I call this.setSelectedFileId
anywhere else in the component it works...what am I missing?
推荐答案
使用 function() {}
而不是 () =>{}
语法(后者将绑定您不想要的 this
):
Use function() {}
instead of () => {}
syntax (the latter will bind this
which you don't want here):
beforeRouteUpdate(to, from, next) {
this.setSelectedFileId(to.params.id);
next();
}
或
beforeRouteUpdate: function(to, from, next) {
this.setSelectedFileId(to.params.id);
next();
}
这篇关于vue-router beforeRouteUpdate 钩子无法访问`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!