vue-router beforeRouteUpdate 钩子无法访问`this` [英] vue-router beforeRouteUpdate hook can't access `this`

查看:117
本文介绍了vue-router beforeRouteUpdate 钩子无法访问`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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆