'How to pass Dynamic Props through Routes in Vue 3?
I can send static props via <router-link> like so:
parent-component:
<router-link :to="{name: 'child-component'}"></router-link>
child-component:
<template>
<h1>{{ test }}</h1>
</template>
<script setup>
import {defineProps} from "vue";
const props = defineProps({
test: String
})
</script>
router.js:
const router = createRouter({
routes: [
{path: "/child-component", name: "child-component", component: ChildComponent, props: {test: 'hello world'}},
]
});
This correctly displays hello world in the h1 element in child-component. But how do I pass a dynamic element, say a state or prop (parent) through the route?
I've tried:
<router-link :to="{name: 'child-component'}" :props="{test: 'did this come through?'}"></router-link>
or
<router-link :to="{name: 'child-component'}" :test="'did this come through?'"></router-link>
But I don't know what to put instead of hello world:
const router = createRouter({
routes: [
{path: "/child-component", name: "child-component", component: ChildComponent, props: {test: 'hello world'}},
]
});
Solution 1:[1]
Here it is, Router link
<router-link
:to="{
name: 'child-component',
params: { id: id, name: name },
}" >test
</router-link>
// Id and name are dynamic value
route.js file
const router = createRouter({
routes: [
{path: "/child-component/:id/:name", name: "child-component", component: ChildComponent},
]
})
You can access the params at the child component
<span>Name: {{ $route.params.name }} Id: {{ $route.params.id }}
</span>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fikremariam Asmro |
