注意:
1.vue2获取实例的方法和vue3不一样
在vue2写法中
<router-view @get-tabs="getTabs" ref="chirdrentRef"/>
this.$refs.chirdrentRef.changTabs(v.name)
vue3写法
<router-view v-slot="{Component}">
<component ref="chirdrentRef" :is="Component" @get-tabs="getTabs"></component>
</router-view>
父路由
<template>
<el-row>
<div class="left">
<div v-for="(v,index) in list" :key="index" class="menuItem" :class="{'active': index == active}" @click="clickMenu(v,index)">
{{ index }}
</div>
</div>
<div class="right">
<span v-for="v in tabs" :key="v" @click="changTabs(v)">{{ v }}</span>--{{ activeTab }}
<!-- <router-view @get-tabs="getTabs" ref="chirdrentRef"/> -->
<router-view v-slot="{Component}">
<component ref="chirdrentRef" :is="Component" @get-tabs="getTabs"></component>
</router-view>
</div>
</el-row>
</template>
<script>
import { reactive, toRefs, defineComponent, onBeforeMount, watch, inject } from 'vue';
// import { asyncRoutes } from '@/router';
import { useUserStore } from '@/store';
import { useRouter } from 'vue-router';
import router from '../../router';
import { getStorage } from '@/utils/storageData';
export default defineComponent({
components: {},
setup() {
const { errorImg, afterLogout, menus } = useUserStore();
const router = useRouter();
const state = reactive({
chirdrentRef: null,
tabs: [],
list:[
{
path: '/test'
},
{
path: '/test1'
},
]
});
watch(
() => router,
() => {
},
{ deep: true, immediate: true }
);
const getTabs = (v)=>{
state.tabs = v;
state.activeTab = v[0].name;
}
return {
...toRefs(state),
getTabs,
};
},
methods: {
clickMenu(v,index){
this.tabs = null;
this.active = index;
router.push(v.path)
},
changTabs(v){
this.activeTab = v.name;
this.$refs.chirdrentRef.changTabs(v.name)
// setTimeout(() => {
// console.log(this.chirdrentRef.changTabs,'...')
// }, 1000);
// this.chirdrentRef.changTabs(v.name);
}
}
});
</script>
<style lang="scss" scoped>
.left{
width: 200px;
}
.menuItem{
width: 100%;
height: 40px;
line-height: 40px;
background: pink;
color: #fff;
margin-bottom: 20px;
&.active{
color: red !important;
}
}
</style>
子路由
<template>
<div>test页面11</div>
</template>
<script>
import { reactive, toRefs, defineComponent, onMounted, provide } from "vue";
export default defineComponent({
components: {},
setup(props,{ emit }) {
const state = reactive({
form:{
name:"",
},
queryData:{
pageIndex: 1,
pageSize: 10,
},
tableData:[],
tabs:[
{
text: 'tab1',
name: 'h',
},
{
text: 'tab2',
name: 'hh'
},
]
})
onMounted(()=>{
fetchData();
})
const fetchData = async ()=>{
console.log("哈哈哈哈")
emit("get-tabs",state.tabs)
}
const changTabs = (name)=>{
console.log("我是tabs切换",name)
}
return {
...toRefs(state),
fetchData,
changTabs,
};
},
methods:{}
})
</script>
<style scoped>
</style>