Chris
Chris

Reputation: 3461

how to execute jQuery code when route is visited?

I have an off-canvas menu that gets drawn in once a Vue route is clicked using jQuery, like so:

$('.order-drawer').show();
$('body').toggleClass( 'order-drawer-open' );

My route is very simple and is displayed as follows:

<router-link to="/order" exact class="order-drawer-toggler">
    <a>Order Now</a>
</router-link>

<router-view></router-view>

Now, how can I make sure that when http://test.dev/test/#/order is viewed in the browser, that then my jQuery calls are getting executed? How can I call a function onload of a route view?

Edit: My routes file looks as follows:

import VueRouter from 'vue-router';

let routes = [
    {
        path: '/order',
        component: require('./views/Order.vue')
    }
];

export default new VueRouter({
    routes
});

Upvotes: 1

Views: 609

Answers (1)

David L
David L

Reputation: 33815

You should allow your routing to drive your component and in that component, drive the jQuery behavior.

import VueRouter from 'vue-router';

let routes = [
    {
        path: '/order',
        component: require('./views/Order.vue')
    }
];

export default new VueRouter({
    routes
});

Order.vue

export default {
    mounted() {
        $('.order-drawer').show();
        $('body').toggleClass( 'order-drawer-open' );
    }
}

When the component is created and mounted, it will show the drawer. There is nothing more you need to do. When vue-router routes TO the route, it will create and mount the component and your jQuery functions will be called.

Upvotes: 1

Related Questions