Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign refs to child components using VueRouter - Vue

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>
like image 531
Sal Avatar asked Oct 20 '25 16:10

Sal


1 Answers

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>

demo

like image 137
tony19 Avatar answered Oct 23 '25 07:10

tony19