路由子组件通知父组件实现
Framework.vue中通过路由出口<router-view/>,展示了Main.vue组件,但是现在需要在Main.vue组件中去调用Framework.vue组件中的方法,可以有以下几种做法文章来源:https://www.toymoban.com/news/detail-525827.html
可以使用provide/inject的机制
Framework.vue
<template>
<div>
framework.vue
<router-view/>
</div>
<template>
<script>
import { ref, reactive, getCurrentInstance, nextTick, watch, provide } from 'vue'
provide('testFun',()=>{
console.log('framework testFun()..');
})
</script>
Main.vue
<template>
<div class="main">
<el-button @click="testFun">tt</el-button>
</div>
<template>
<script>
import { ref,reactive, nextTick, inject } from 'vue'
let testFun = inject('testFun')
</script>
可以直接在<router-view @kk=“kk”/>绑定事件监听
Framework.vue
<template>
<div>
framework.vue
<router-view @kk="kk"/>
</div>
<template>
<script>
import { ref, reactive, getCurrentInstance, nextTick, watch, provide } from 'vue'
const kk = () =>{
console.log('kk');
}
</script>
Main.vue
<template>
<div class="main">
<el-button @click="testKK">KK</el-button>
</div>
</template>
<script setup>
import { ref,reactive, nextTick, inject } from 'vue'
const emit = defineEmits([
'kk'
])
const testKK = ()=>{
emit('kk')
console.log('testKK') // 先触发父组件的自定义事件, 调用父组件中绑定的方法之后,再执行的此次打印testKK
}
</script>
<style lang="scss"></style>
可以使用<router-view />的组件写法
Framework.vue
<template>
<div>
framework.vue
<router-view v-slot:="{Component,route}">
<component @kk="kk" :is="Component" :key="route.path"/>
</router-view>
</div>
<template>
<script>
import { ref, reactive, getCurrentInstance, nextTick, watch, provide } from 'vue'
const kk = () =>{
console.log('kk');
}
</script>
Main.vue
<template>
<div class="main">
<el-button @click="testKK">KK</el-button>
</div>
</template>
<script setup>
import { ref,reactive, nextTick, inject } from 'vue'
const emit = defineEmits([
'kk'
])
const testKK = ()=>{
emit('kk')
}
</script>
<style lang="scss"></style>
父组件中调用路由子组件中的方法
可参考:vue3 调用router-view下的组件方法文章来源地址https://www.toymoban.com/news/detail-525827.html
- 有的时候,我们需要在当前组件组件中,调用路由子组件中的方法(之前都是直接引入的子组件,然后通过ref引用该子组件,然后通过ref直接调用,但是注意这里的区别是:
路由子组件,而非在父组件中直接使用的子组件
) - 首先,可以确定的是子组件必须将供外界调用的方法暴露出去
- 不能直接在<router-view/>中直接使用ref然后调用,这里拿到的组件实例并非路由子组件,因而不能调用子组件中的方法
- 使用<router-view/>的组件写法,才可以使用ref引用到路由子组件
Framework.vue
<template>
<div>
framework.vue
<el-button @click="triggerJJ">触发路由子组件的jj方法?</el-button>
<router-view v-slot:="{Component,route}">
<component ref="routerViewRef" :key="route.path"/>
</router-view>
</div>
<template>
<script>
import { ref, reactive } from 'vue'
const routerViewRef = ref()
const triggerJJ = () => {
routerViewRef.value.jj()
}
</script>
Main.vue
<template>
<div class="main">
main-jj
</div>
</template>
<script setup>
import { ref,reactive, nextTick, inject } from 'vue'
const jj = ()=>{
console.log('main');
}
defineExpose({
jj
})
</script>
<style lang="scss">
</style>
到了这里,关于vue3 父组件与路由子组件相互调用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!