1đź‘Ť
Vue router provides several functions for programmatic navigation.
this.$router.go(n)
The go(n)
function expects n
to be a number
and is the number of steps forward or backward in the history to travel. I think this is the reason you’re not getting the result you expect.
this.$router.push(path|route)
If you’d like to supply an actual path to the function, you should use push()
instead of go()
. For example to go to the “home” page you might use this.$router.push('/')
or to go to the profile page this.$router.push('/profile')
. Importantly, when you use push()
the path you submit gets added onto the history stack.
this.$router.replace(path|route)
If you do NOT want to add an entry to the history stack, you should use replace()
instead of push()
. Otherwise, the usage of replace()
is the same as push()
, i.e. this.$router.replace('/')
or this.$router.replace('/profile')
.
Using a path
vs using a route
object
When navigating with push(path|route)
and replace(path|route)
you have the option to use a path
, which is just a string that is the URL of the place you want to go, or using a route
object. The route object gives you a lot more control and allows you to send route or query parameters to the destination component.
For example, if you want to navigate to the profile page for the user with an id
of 3
, you could do something like this.$router.push({ path: '/profile', params: { id: 3 } })
. Alternatively, if you’re using a named route, you could substitute the route name for the path, i.e. this.$router.push({ name: 'profile', params: { id: 3 } })
. The name
should correspond to the name assigned to the route wherever you’ve set up your main Router
instance.
Using Vuetify’s v-btn
component
If you’re using a Vuetify button component there is NOT a router
attribute. Instead you’d just specify the to
attribute and Vuetify should automatically interpret it as if it were a router-link
, e.g. <v-btn to="/profile">My Profile</v-btn>
. Alternatively, you can use a route
object, e.g. <v-btn :to="{ path: '/profile', params: { id: 3 } }">Profile</v-btn>
. Importantly, notice the colon (:
) preceding the to
in the second case. This tells Vue to interpret the attribute value as JavaScript instead of plain text.