Ilya Manyahin
Ilya Manyahin

Reputation: 238

How to delay the mounted event

App in created event execute AJAX request to server to get a status. In mounted event App fire onLoad callback with the status to let Developer decide what to do next.

Depends on the status App should redirect user or display message. Until AJAX in progress User should see loading icon.

Here is async problem. In created event a request already sent and app fired mounted, but the request still running in background. And Developer receive default status.

How to wait for status from backend and only after fire mounted event?

Upvotes: 3

Views: 6486

Answers (3)

Mervyn
Mervyn

Reputation: 583

Another simple method is use v-if,like this:

<div class="status" v-if="requestDone">status</div>
<div class="loading" v-else>loading</div>

In js:

data() {
    return {
        requestDone: false
    }
}

created() {
    promise.then(() => {
        ...
        this.requestDone = true
    })
}

status wrap will render until requestDone becomes true.

Upvotes: 2

DanPottsHimself
DanPottsHimself

Reputation: 136

If you really feel like you need to delay the mounted cycle: When looking at the lifecycle here, it states if there is no 'el' option on the component, then you can manually call mount using vm.$mount(el).

However, could you not use the beforeUpdate lifecycle hook? So rather than delaying the mount function (delaying the component from mounting seems like a bad idea), you return the request data which triggers the beforeUpdate?

Upvotes: 3

divine
divine

Reputation: 4912

Better approach to handle this scenario is to use NavigationGuards in vue-router .

beforeRouteEnter helps to decide whether a particular component associated to the router should be loaded or it has to be navigated to another route before the component is loaded.

beforeRouteEnter Comes with next handler. Only when next is invoked, the component will be loaded. This guard is a perfect area for AJAX requests.

next()/next(true) - proceed with navigation. This can be used when promise is resolved

next(false) - navigation does not occur.

 beforeRouteEnter (to, from, next) {
    // called before the route that renders this component is confirmed.
    // does NOT have access to `this` component instance,
    // because it has not been created yet when this guard is called!
  },

Once the route navigation is decided by beforeRouteEnter guard component lifecycle hooks like created() or mounted() can be invoked for further actions

Reference: https://router.vuejs.org/en/advanced/navigation-guards.html

Upvotes: 1

Related Questions