How to programmatically navigate using router in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to navigate users programmatically using the $router.

Users can navigate through the website by clicking the <a> tags but you can also do that programmatically.

You can navigate users programmatically after a certain condition is met, e.g. user filled the form or doesn’t have access to the page.

Router.push()

You can use a router.push() method of the router instance. See the examples below:

// literal string path
router.push('home')

// object
router.push({ path: 'home' })

// named route
router.push({ name: 'user', params: { userId: '123' } })

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })

Router.push() example

Let’s suppose there’s a form that user just filled in. If there’re no errors the user should be taken to the homepage. We can do that by first validating the form and then using the router.push() method to navigate the user to the homepage. See the example below:

methods: {
  submit() {
    if (this.$refs.form.validate()) {
      router.push({ path: 'home' })
    }
  }
}

Hi, I'm Renat 👋

 


You can also use additional parameters e.g. userId etc.

If you find this post useful, please let me know in the comments below and subscribe to my newsletter. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-navigate-programmatically

PS: Make sure you check other Vue.js tutorials, e.g. how to select an HTML element in Vue.js or redirect to login page in Vue.js.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment