使用 VueRouter 为子组件分配 refs - Vue

Assign refs to child components using VueRouter - Vue

我的 Vue webapp 中的 main.js 文件中有以下代码:

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
});

目前,路由和组件渲染工作得很好,但是从我的 MainComponent 来看,我想在子组件中触发一个方法。我知道我可以在 Vue 中使用 refs 来做到这一点,但是我不确定如何使用 VueRouter 创建它们,因为组件正在由 VueRouter 加载。这是我的 MainComponent.js:

<template>
  <div id="main">
    <h1>Main Component</h1>
    <router-view></router-view>
  </div>
</template>

router-view 上的模板引用将自动应用于视图的渲染组件。使用该模板引用,您可以直接访问 child 的方法:

<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