我的 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
上的模板引用将自动应用于 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>
关于javascript - 使用 VueRouter 为子组件分配 refs - Vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67596944/