Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Programmatically Navigate to Routes with Vue Component Methods

    Laurie BarthLaurie Barth

    We can navigate programmatically using functions in JavaScript. We can use explicit paths, or pass params and use a route name.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 0:01 We'll start by navigating with a template button. We'll map this using the onClick to a function called toEgghead. We'll define the function as a method. Inside the function, we'll use JavaScript to access our router object, this.$.router. Then, we can push a new route onto our router /egghead. If we refresh the page and click on the button, we'll be navigated to our egghead page.

    0:54 Alternatively, we may want to access our blog page, which comes with an ID parameter. Let's change our function to toBlog.

    1:07 Now, instead of pushing /egghead, we'll push /blog with the argument ID. We can set a constant that will pass in and set that ID for us. In this case the constant will be 1234. If we refresh and click again, we'll see that we navigated to blog 1234.

    1:42 Alternatively, we can push an object onto our router array. Let's try doing that with path blog and param ID. If we try again, we realize that it doesn't work. This is because path and params can't be combined. If we want to do it in this manner, we need a name on our route record.

    2:22 We'll call it blog. Now we can set name toBlog and use params, and we'll navigate there successfully.