Reputation: 191
I have code like:
<template>
<router-view />
</template>
<script setup lang="ts">
...
const product: Ref<IProduct|undefined>: ref();
...
</script>
I need to pass product
as a prop to the component which loads in router-view
.
Some time ago it was possible just like <router-view :an-prop="product" />
, but since new version of Vue was released I've got warning:
Extraneous non-props attributes (product) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.
Maybe I'm blind, but I honestly didn't find anything about it in the official documentation, only trivial examples of using <router-view>
and billions of trivial examples of using vue-router programmatically. After hours of experiments and studies search engines' results I found out that now router-view
uses slots
and end up with such code:
<router-view v-slot="{ Component }">
<component :is="Component" />
</router-view>
Which gave me not much, actually. Anyway I don't understand what to do next. Is there any way to pass props to an component rendering via RouterView nowadays in vue3?
Upvotes: 2
Views: 2520
Reputation: 369
Just tested with a new vue 3 project. It works just fine passing it directly to the RouterView. Then any component rendered by the RouterView will have access to that prop.
Example:
router/index.js
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",
name: "default",
component: () => import("../views/HomeView.vue"),
},
{
path: "/home",
name: "home",
component: () => import("../views/HomeView.vue"),
},
{
path: "/about",
name: "about",
component: () => import("../views/AboutView.vue"),
},
],
});
export default router;
App.vue
<template>
<header>
<nav>
<RouterLink to="/home">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</header>
<RouterView :product="product" />
</template>
<script setup>
import { RouterLink, RouterView } from "vue-router";
import { ref } from "vue";
const product = ref({ name: "bmw e46" });
</script>
HomeView.vue
<template>
<div class="about">
<h1>This is home page</h1>
<p>{{ product.name }}</p>
</div>
</template>
<script setup>
defineProps({
product: { type: Object },
});
</script>
AboutView.vue
<template>
<div class="about">
<h1>This is about page</h1>
<p>{{ product.name }}</p>
</div>
</template>
<script setup>
defineProps({
product: { type: Object },
});
</script>
Upvotes: 2