Shankar
Shankar

Reputation: 2825

what is the equivalent of watchEffect in VueJS 2

In a VueJS 2 component, I populate a props variable when the component is loaded.

  created() {
    this.events = null
    Service.getEvents()
      .then(response => {
        this.events = response.data
      })
      .catch(error => {
        console.log(error.response)
      })
  }
}

I need to reload the component with "events" props when a next page is clicked. I saw a VueJS 3 tutorial, where the props variable is reloaded using the watchEffect method (https://v3.vuejs.org/guide/reactivity-computed-watchers.html#watcheffect)

What is the equivalent of this functionality in VueJS 2?

I tried to use the watch() method for this variable, but that causes an infinite recursion because the "events" object is changed inside the method.

//Error - recusrsion
watch: {
    events() {
    this.events = null
    Service.getEvents()
    .then(response => {
              console.log(response.data)
              this.events = response.data
            })
    .catch(error => {
              console.log(error.response)
            })
        }
    },

How can we reload the events in the same page when user clicks a button/link?

Upvotes: 0

Views: 1044

Answers (2)

Stiegi
Stiegi

Reputation: 1805

watch in the options api receives the old and the new value:

watch: {
    event: function (oldEventData, newEventData) {
        console.log(newEventData) // do something with new event data
    }
},

Upvotes: 1

jinseok.oh
jinseok.oh

Reputation: 233

on your code this.events mean the variable of watch...

so it cause recursion.

if you want to add event on click next page,

then add @click= event props on component of next page props

Upvotes: 1

Related Questions