繁体   English   中英

如何在可重用的方法中使用 vue-router

[英]How to use vue-router in a reusable method

我正在尝试能够在我的应用程序中需要的地方重用我的代码段。 这段代码对vue-router的路径做了条件。

为此,我创建了一个文件“utils.js”:

const util = {
  nextStepAtelier () {
    if (this.$route.path.includes(this.user.event_1.slug)) {
      this.$router.push(`/events/${this.user.event_1_2.slug}/step-1`)
    }

    if (this.$route.path.includes(this.user.event_1_2.slug)) {
      this.$router.push(`/games/game-1/step-1`)
    }

  }
};

export default util;

在我的step-3.vue ,我像这样调用我的nextStepAtelier()

import util from '~/utils/utils'
export default {
   computed: {
          user() {
              return this.$store.getters['auth/user']
          }
        },
   methods: {
            nexstStep() {
                util.nextStepAtelier();
            }
        }
}

它不起作用。 我有与 view-router 相关的错误Cannot read property 'path' of undefined 看起来它没有正确分析 vue-router。

我指定当我直接在step-3.vue制作此代码时,它可以工作

谢谢

您需要导入路由器,您无权访问 js 文件中的全局$router 只需放在文件的顶部: import router from './router.js' (或任何路径)然后将$router更改$router router (删除“this”)

由于this在您的 util 对象内部是不同的,您可以让 nextStepAtelier 接受路由器实例作为参数,然后使用util.nextStepAtelier(this.$router)调用它

然后你可以使用router.currentRoute访问当前路由(而不是this.$route

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM