Bitwise
Bitwise

Reputation: 8461

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!

Upvotes: 16

Views: 25824

Answers (2)

Ben
Ben

Reputation: 337

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

Upvotes: 6

Decade Moon
Decade Moon

Reputation: 34306

If your computed property current_user_has_team depends on data which is not available until after the axios call, then you need to either:

  1. In the current_user_has_team property, if the data is not available then return a sensible default value.
  2. Do not access current_user_has_team from your template (restrict with v-if) or anywhere else until after the axios call has completed and the data is available.

It's up to you how you want the component to behave in "loading" situations.

Upvotes: 18

Related Questions