Vue3 子路由vue如何调用父路由vue中的方法?
1. router -> index.ts 文件:
import { createRouter, createWebHistory } from 'vue-router'
import DefaultView from '@/views/default/index.vue'
import ParentView from '@/views/parent/index.vue'
import ChildView from '@/views/child/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'Default',
component: DefaultView
},
{
path: '/parent',
name: 'parent',
component: ParentView,
children: [
{
path: 'child',
name: 'child',
component: ChildView
}
]
}
]
})
export default router
2、父路由 ParentView 对应的 index.vue 界面
<template>
<div>
<span>父路由界面</span>
<!-- 下面 route-view 是子路由承载标签 -->
<router-view></router-view>
</div>
</template>
<script setup lang="ts">
import { onMounted, provide } from 'vue'
//使用 provide 方法向子路由公开 CallParent 方法
provide('CallParent', (data: any) => {
console.log('成功调用了父路由方法');
})
onMounted(() => {
//父路由界面元素加载完毕
})
</script>
3、子路由 ChildView 对应的 index.vue 界面
<template>
<div>
<span>子路由界面</span>
</div>
</template>
<script setup lang="ts">
import { onMounted, inject } from 'vue'
//使用 inject 获取到父路由公开 CallParent 方法
let parentMethod: (data: any) => {} = inject('CallParent')
onMounted(() => {
//调用父路由中的方法
parentMethod('hello world!')
})
</script>