Agu Dondo
Agu Dondo

Reputation: 13609

Vue.js Router: Run code when component is ready

I'm working on a single-page app with Vue.js and its official router.

I have a menu and a component (.vue file) per every section which I load using the router. In every component I have some code similar to this:

<template>
    <div> <!-- MY DOM --> </div>
</template>

<script>
    export default {
        data () {},
        methods: {},
        route: {
            activate() {},
        },
        ready: function(){}
    }
</script>

I want to execute a piece of code (init a jQuery plugin) once a component has finished transitioning in. If I add my code in the ready event, it gets fired only the first time the component is loaded. If I add my code in the route.activate it runs every time, which is good, but the DOM is not loaded yet, so is not possible to init my jQuery plugin.

How can I run my code every time a component has finished transitioning in and its DOM is ready?

Upvotes: 4

Views: 14564

Answers (3)

Dheeraj
Dheeraj

Reputation: 83

You can use

mounted(){
  // jquery code
}

Upvotes: 1

JJPandari
JJPandari

Reputation: 3522

Though this may be a bit late... If I guess correctly, the component having problem stays on the page when you navigate between routes. This way, Vue reuses the component, changing what's inside it that needs to change, rather than destroy and recreate it. Vue provides a key attribute to Properly trigger lifecycle hooks of a component. By changing a component's key, we can indicate Vue to rerender it. See key in guide for details and key in api for code sample.

Upvotes: 0

maoosi
maoosi

Reputation: 301

As you are using Vue.js Router, it means that each time you will transition to a new route, Vue.js will need to update the DOM. And by default, Vue.js performs DOM updates asynchronously.

In order to wait until Vue.js has finished updating the DOM, you can use Vue.nextTick(callback). The callback will be called after the DOM has been updated.

In your case, you can try:

route: {
    activate() {
        this.$nextTick(function () {
            // => 'DOM loaded and ready'
        })
    }
}

For further information:

Upvotes: 2

Related Questions