javascript - 使用 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>
解决方案
上的模板引用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>
推荐阅读
- mongodb - Mongoose:使用一个用户的管理员权限在不同的 Mongo 数据库上进行身份验证
- c - 在 C 中具有多个进程的 TCP Echo 服务器
- python - Python 中可变嵌套字典的类型提示
- macos - 在 macOS 上构建支持 X11 的 Firefox
- c# - 如何使用 C# 函数返回列表数组?
- wordpress - 命名空间时扩展 WC_Product 变量
- flutter - 文件选择器和文件选择器交叉构建失败,即使尝试了所有命令也没有接受许可证
- ios - `YogaKit.modulemap not found` 阻止 iOS 构建
- javascript - 有没有办法使用 SSE 流式传输 XHTML 而不是文本?
- python - 如何从 bagging 中获得集合的基本模型分数