Home > Blockchain >  Vue 3 and Vue Router 4 How to pass prop when using router-view only for specific component
Vue 3 and Vue Router 4 How to pass prop when using router-view only for specific component

Time:04-16

I have basic routing and props working but the way I have it, the msg prop will be sent to every component loaded by the router? Is there a way around this?

App.vue is my base component

<template>
    <div>
        <img alt="Vue logo" src="./assets/logo.png" />
        <router-view msg="Hello Foo"></router-view>
    </div>
</template>

<script>
export default {
    name: 'App',
};
</script>

This is my HomePage.vue component

<template>
    <div >
        <h1>{{ msg }}</h1>
    </div>
</template>

<script>
export default {
    name: 'HomePage',
    props: {
        msg: String,
    },
};
</script>

And here is my routes.js

import * as VueRouter from 'vue-router';
import HomePage from './components/HomePage';

const routes = [
    {
        name: 'HomePage',
        path: '/',
        component: HomePage,
    },
];

const router = new VueRouter.createRouter({
    history: VueRouter.createWebHistory(),
    routes,
});

export default router;

I would like to know is there a way to dynamically send different props depending on which route/component is loaded?

CodePudding user response:

You could configure a route meta field just for specific routes:

// router.js
import { createRouter } from 'vue-router'
import HomePage from '@/views/HomePage.vue'

export default createRouter({
  routes: [
    {
      name: 'HomePage',
      path: '/',
      component: HomePage,

                  
  • Related