简体   繁体   中英

Assign refs to child components using VueRouter - Vue

I have the following code in my main.js file in my Vue webapp:

const routes = {
  path: "/main", redirect: "/main/home", name: "Main", 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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM