Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run computed function after mounted - VUE

I'm trying to run a function that needs some data that I get back from the mounted method. Right now I try to use computed to create the function but unfortunately for this situation computed runs before mounted so I don't have the data I need for the function. Here is what I'm working with:

    computed: {
      league_id () {
        return parseInt(this.$route.params.id)
      },
      current_user_has_team: function() {
        debugger;
      }
    },
    mounted () {
      const params = {};

      axios.get('/api/v1/leagues/' +this.$route.params.id, {
        params,
        headers: {
          Authorization: "Bearer "+localStorage.getItem('token')
        }
      }).then(response => {
        debugger;
        this.league = response.data.league
        this.current_user_teams = response.data.league
      }).catch(error => {
        this.$router.push('/not_found')
        this.$store.commit("FLASH_MESSAGE", {
          message: "League not found",
          show: true,
          styleClass: "error",
          timeOut: 4000
        })
      })
    }

As you can see I have the debugger in the computed function called current_user_has_team function. But I need the data I get back from the axios call. Right now I don't have the data in the debugger. What call back should I use so that I can leverage the data that comes back from the network request? Thank You!

like image 570
Bitwise Avatar asked May 26 '18 23:05

Bitwise


People also ask

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

Can I use computed in method Vue?

In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.

What is the difference between computed and mounted Vue?

A computed property will only re-evaluate when some of its dependencies have changed. If you want data to be cached use Computed properties on the other hand mounted is a lifecycle hook, a method which is called as soon as the Vue instance is mounted on the DOM.

Is computed property reactive in Vue?

A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as author.books has not changed, multiple access to publishedBooksMessage will immediately return the previously computed result without having to run the getter function again.


1 Answers

If your behavior is synchronous, you can use beforeMount instead of mounted to have the code run before computed properties are calculated.

like image 173
Ben Avatar answered Sep 29 '22 18:09

Ben