开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第十天,点击查看活动详情
题引:
在我们常见PC管理系统中(以vue+element ui为例子),基本都会使用以下的布局实现。
那么问题就来了,nav会记录我们点击过的路由菜单,那么如果我们在此基础上用el-dropdown实现下拉菜单,且要实现路由页面刷新的功能(只针对content区域,而非整体刷新)。那么我们使用路由的go、push、redirect或者window.location.reload等方法是没法实现的,因为它们是整体窗口刷新,因此我用取巧的方式提供了解决的思路,分别有vue2和vue3。
方案:
vue2:
我们可以先在vuex中定义state变量routerActive:true,并且写好对应的mutation方法(UPDATE_ROUTERACTIVE)。 接下来我们找到对应使用router-view的方法。如果使用了keep-alive进行包裹的话,那么把 v-if="$store.state.routerActive"写在keep-alive,否则写在router-view,当然也可以使用template包裹
<template>
<div class="app-cont">
<section class="app-main">
<keep-alive v-if="$store.state.tagsView.RouterActive">
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<template v-if="$store.state.tagsView.RouterActive">
<router-view v-if="!$route.meta.keepAlive"></router-view>
</template>
</div>
</template>
接下来我们找nav文件,找到对应的点击方法。借用nextTick方法进行取反切换。
<template>
<li @click="refreshSelectedTag">刷新</li>
</template>
<script>
export default{
methods:{
refreshSelectedTag(){
this.$store.commit('UPDATE_ROUTERACTIVE',false);
this.$nextTick(()=>{
this.$store.commit('UPDATE_ROUTERACTIVE',true);
})
}
}
}
</script>
这样我们就可以实现局部刷新了
vue3:
如果在vue3版本,我们可以不借用vuex或者pinia,可以直接使用provide/inject来进行传递
<template>
<div class="app-cont">
<section class="app-main">
<keep-alive v-if="RouterActive">
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<template v-if="RouterActive">
<router-view v-if="!$route.meta.keepAlive"></router-view>
</template>
</section>
</div>
</template>
<script>
export default {
name: "AppMain",
data() {
return {
RouterActive:true
}
},
provide(){
return{
relaod:this.reLoad
}
},
methods:{
reLoad(){
this.RouterActive = false;
this.$nextTick(()=>{
this.RouterActive = true;
})
}
}
};
</script>
//组件内使用
<template>
<li @click="refreshSelectedTag">刷新</li>
</template>
<script>
export default {
inject:['reLoad'],
methods:{
refreshSelectedTag(){
this.reLoad()
}
}
}
</script>
以上就是实现局部刷新的方法,希望能为你解决问题。