在"/src/layout/index.vue"的<app-main>组件里面增加代码,<app-main v-if="isRouterAlive">,isRouterAlive的默认值为true。
在index.vue的methods里面增加一个reload()方法
reload() {
this.isRouterAlive = false;
this.$nextTick(function() {
this.isRouterAlive = true;
})
}
使用provide()将reload()方法传递到子组件里面
provide() {
return {
reload: this.reload;
}
},
data() {
return {
isRouterAlive: true;
}
}
下面的代码为子组件layoutIndexLeft.vue的代码
<!-- 在el-menu 的标签里面增加@select="handleSelect"的方法 -->
<el-menu
:background-color="variables.menuBg"
……
@select="handleSelect">
</el-menu>
因为在父组件里面使用了provide将reload方法放出来了,所以使用inject将reload方法接收
inject: ["reload"],
methods: {
handleSelect(index) {
if (index === this.$route.path) {
this.relaod();
// 此reload方法为父组件的代码
// 这里执行了会导致父组件的isRouterAlive改变
// 所以v-if会让<app-main>标签重新加载
}
}
}
本文介绍了一个Vue项目的优化实践,通过在父组件`<app-main>`中使用`v-if`结合`isRouterAlive`状态来控制组件的重新加载。当在子组件`layoutIndexLeft.vue`中触发`handleSelect`方法时,利用`provide/inject`来调用父组件的`reload`方法,实现页面局部刷新,避免全页面重新渲染。这一技巧有助于提高应用性能并保持用户体验的流畅。
1356

被折叠的 条评论
为什么被折叠?



