应用
vue在当前页面内路由参数发生变化,怎么进行页面刷新。
传统方式
- window.location.reload(); 整个页面进行刷新,会出现白屏,体验不好
- this.$router.go(0); 同上,体验不友好
推荐方法
使用provide / inject组合方式
原理:允许一个祖先组件向其子孙后代注入一个依赖,不论组件层次有多深,在起上下游关系成立的时间内始终生效。
provide: 一个对象或者返回一个对象函数
inject: 一个字符串数组,或者一个对象,对象的key是本地的绑定名
实例如下
APP.vue
<template>
<div id="app">
<router-view v-if="isRouterAlive" />
</div>
</template>
<script>
export default {
name: "App",
//提供reload方法
provide(){
return {
reload: this.reload
}
},
data() {
return {
//isRouterAlive控制router-view的显示或隐藏,从而控制页面的再次加载。
isRouterAlive: true
}
},
methods: {
//刷新方法
reload(){
this.isRouterAlive = false;
//该方法会在dom更新后执行
this.$nextTick(function(){
this.isRouterAlive = true;
});
}
}
};
</script>
在需要刷新的子组件页面,注入App.vue组件提供(provide)的 reload 依赖,直接this.reload()调用,即可刷新当前页面。
<script>
export default {
name: '',
//注入reload
inject: ['reload'],
//实例的数据对象
data() {
return {
}
},
//方法
methods: {
},
//生命周期函数
created() {
},
beforeMount() {
},
mounted() {
},
//监视
watch: {
//检测路由参数发生改变时,刷新当前页面
'$route': function(){
this.reload();
}
},
//过滤器
filters: {},
//自定义指令
directive: {}
}
</script>
参考:https://segmentfault.com/a/1190000017007631