简体   繁体   中英

How to use vue-router in a reusable method

I'm trying to be able to reuse my piece of code where I need it in my app. This piece of code makes conditions on the path of vue-router.

To do this, I created a file "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;

And in my step-3.vue , I call my nextStepAtelier() like that :

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

It doesn't work. I have errors related to view-router Cannot read property 'path' of undefined . It looks like it is not properly analyzing vue-router.

I specify that when I make this code directly in step-3.vue , it works

Thank you

You need to import the router, you don't have access to the global $router inside your js file. Just put on the top of the file: import router from './router.js' (or whatever the path is) then change $router to router (remove "this")

Since this is different inside your util object, you can have nextStepAtelier accept the router instance as a parameter then call it with util.nextStepAtelier(this.$router)

Then you can access the current route with router.currentRoute (instead of this.$route )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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