Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
Agu Dondo Avatar asked Oct 16 '25 04:10

Agu Dondo


2 Answers

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:

  • https://vuejs.org/api/#Vue-nextTick
  • https://vuejs.org/guide/reactivity.html#Async-Update-Queue
like image 94
maoosi Avatar answered Oct 17 '25 16:10

maoosi


You can use

mounted(){
  // jquery code
}
like image 44
Dheeraj Avatar answered Oct 17 '25 18:10

Dheeraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!