vue如何通过ref调用router-view子组件的方法
作者:程序员小小黑
这篇文章主要介绍了vue 通过ref调用router-view子组件的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
vue 通过ref调用router-view子组件的方法

由于用的vue2.7版本,但用了vue3 setup的语法;
注意:是vue2的template结构,vue3的setup语法;非这种情况需要举一反三。
处理方案:
1、对router-view加上ref template修改
直接对router-view加上ref,<router-view ref="child" > </router-view>script修改
  // add方法
  function add(){
    // 成功后调用子组件(此)
    proxy.$refs.child.refreshList
   }
  // add方法
  function add(){
    // 成功后调用子组件(此)
    proxy.$refs.child.refreshList
   }2、子组件暴漏方法
注意:一定要用【defineExpose】暴漏给父级,否则父级看不到这个方法
script内:
function refreshList() {
}
// 暴漏给父组件
defineExpose({
 refreshList
})其他场景的:
3、纯vue2的
应该this.$refs.child.refreshList就成, 因为子组件用的是 methods定义的
4、纯vue3的
父组件template修改
<template>
  <router-view v-slot="{ Component }">
    <component ref="child" :is="Component" />
  </router-view>
</template>父组件script修改
  // add方法
  function add(){
    // 成功后调用子组件(此)
    proxy.$refs.child.refreshList
   }子组件script修改注意:一定要用【defineExpose】暴漏给父级,否则父级看不到这个方法
function refreshList() {
}
// 暴漏给父组件
defineExpose({
  refreshList
})到此这篇关于vue 通过ref调用router-view子组件的方法的文章就介绍到这了,更多相关vue ref调用子组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
