Passing props with Vue.js programmatic navigation
I have a Vue component that has a pointer named 'title' like:
<script>
export default {
props: ['title'],
data() {
return {
}
}
}
</script>
I am navigating to a component programmatically after completing a certain action. Is there a way to programmatically route the user while setting the prop value at the same time? I know that you can create a link like this:
<router-link to="/foo" title="example title">link</router-link>
However, is there a way to do something like the following?
this.$router.push({ path: '/foo', title: 'test title' })
EDIT:
As I said, I changed my route to the following:
{
path: '/i/:imageID',
component: Image,
props: true
}
And moving on to the next one:
this.$router.push({ path: '/i/15', params: {title: 'test title' }})
However, my image component (template - see below) still has no name.
<h1>{{ title}}</h1>
Is there something that might be causing the problem?
source to share
Use parameters.
this.$router.push({ name: 'foo', params: {title: 'test title' }})
Note. You must specify name
. It doesn't work if you call this.$router.push
with path
.
And set a route to receive parameters as props.
{path: "/foo", name:"foo", component: FooComponent, props: true}
props: true
documented here .
source to share
The vue-router docs clearly state that params
it only works with name
, not with path
.
// set props: true in your route definition
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId }}) // -> /user
If you are using path
, pass parameters in the path itself or use query
as shown below:
router.push({ path: '/user/${userId}' }) // -> /user/123
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
source to share
The same problem is encountered with child routes defined in the router. Below in router.js shows child routes mapped to named
<router-view name="create"></router-view>
<router-view name="dashboard"></router-view>
router.js
{
path: "/job",
name: "Job",
component: () => import("./views/JobPage"),
children: [
{
path: "create",
name: "JobCreate",
components: {
create: JobCreate
}
},
{
path: ":id",
name: JobConsole,
components: {
dashboard: JobConsole
}
}
]
},
When I try to pass props from create, vue-router fails to get the dynamic route mapping needed by JobConsole:
this.$router.push(
{
name: "Job",
params: {
id: this.ID_From_JobCreate
}
)
source to share