Reputation: 1697
I have the following code in my main.js
file in my Vue webapp:
const routes = {
name: "Main",
path: "/main",
redirect: "/main/home",
component: MainComponent,
children: [
{ path: "home", name: "Main_Home", component: MainHomeComponent },
{ path: "play", name: "Main_Play", component: PlayComponent },
]
}
Vue.config.productionTip = false;
const router = new VueRouter({
mode: 'history',
routes
});
Currently, the routing and component rendering is working really well, however from my MainComponent
, I want to trigger a method within a child component. I understand that I can do that with refs
in Vue, however I'm not sure how I can create them with VueRouter
, as the components are being loaded by VueRouter
. Here is my MainComponent.js
:
<template>
<div id="main">
<h1>Main Component</h1>
<router-view></router-view>
</div>
</template>
Upvotes: 4
Views: 2935
Reputation: 138526
A template ref on the router-view
will automatically apply to the view's rendered component. With that template ref, you could access the child's method directly:
<template>
<div id="main">
<h1>Main Component</h1>
<button @click="callChildMethod">Call child method</button>
<router-view ref="view"></router-view>
</div>
</template>
<script>
export default {
methods: {
callChildMethod() {
this.$refs.view.myMethod()
}
}
}
</script>
Upvotes: 4