1

I would like to know how can I change this

computed: {
    currentUrl () {
      return this.$route.path
    },
  },
  watch: {
    currentUrl (newURl, firstUrl) {
      if ((!this.$cookiz.get('firstUrl')) && ((this.check === undefined) || (this.check === 0))) {
        this.showPopUp()
      }
    }
  },

with a watch that stops once after detect the first change or the url. Any idea would be appreciated. Thanks a lot.

MFL
  • 37
  • 4

1 Answers1

0

Instead of creating a watcher inside watch, create it inside the created hook and then remove it by calling itself:

created() {
  this.unwatchCurrentUrl = this.$watch('currentUrl', (newURl, firstUrl) => {
    const condition1 = !this.$cookiz.get('firstUrl')
    const condition2 = this.check === undefined
    const condition3 = this.check === 0
    if (condition1 && (condition2 || condition3)) {
      this.showPopUp()

      // Remove watcher
      this.unwatchCurrentUrl()
    }
  })
}
AlekseyHoffman
  • 2,438
  • 1
  • 8
  • 31
  • But one question, I added a console log before the 3 consts. The idea of this kind of watch functions is that once execute never be used again, but if I change the url the console log appears on my console every time. Is it correct? – MFL May 06 '20 at 14:19
  • @MiguelFernándezLizarbe add `console.log('test')` inside the `if` statement. Is it ever get called? If not, it means that the condition in the `if` statement never equal to `true`, so functions `this.showPopUp()` and `this.unwatchCurrentUrl()` never called. Make sure the condition is equal to `true` – AlekseyHoffman May 06 '20 at 14:32
  • great, now it works perfect, thank you so much – MFL May 06 '20 at 14:44