Vue: Pass Arbitrary Data to a Vue Route
Doing a programmatic route change using Vue Router is very straight forward:
this.$router.push({name: 'home'}) // Triggers the 'home' route
However, I couldn't find the "correct" way to pass arbitrary data to this route.
My use case just didn't make sense to have the data show in the URL, so params
and query
options were not applicable. There is a way to use props in routes, but that doesn't seem to be possible when doing a programmatic route change. There's the meta
field, but that's not quite the right choice either.
After a lot of dead ends on Stack Overflow and other articles, I settled for going with params. To my surprise, you don't have to define params in order to use them and there's no change made to the URL. Here's what that means:
// My route does not have params defined...
const routes = [
{
path: '/',
name: 'home',
component: Home,
meta: {title: 'Home'}
},
...
]
// but when triggering a route change, I can still set params and they go through
this.$router.push({name: 'home', , params: {foo: 'bar' }})
// In the home view those params are available...
this.$route.params.foo // "bar"
Using params
, even though the route doesn't define them, is nice and clean and it totally works, but still feels a bit incorrect to me. If you know something about passing arbitrary data in Vue Router, please share!