⚠️ This lesson is retired and might contain outdated information.

Programmatically Navigate to Routes with Vue Component Methods

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 months ago

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

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.

egghead
egghead
~ 44 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today