首页 > 解决方案 > 使用 VueRouter 将 refs 分配给子组件 - Vue

问题描述

main.js我的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 });

目前,路由和组件渲染工作得非常好,但是从我的MainComponent,我想在子组件中触发一个方法。我知道我可以refs在 Vue 中做到这一点,但是我不确定如何VueRouter使用VueRouter. 这是我的MainComponent.js

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

标签: javascriptvue.jsreferencevue-router

解决方案


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

<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>

演示


推荐阅读