vue——实现刷新页面的功能
场景
在Vue项目中,经常会遇到刷新当前页面的需求,此时可以借助vue组件中path路径地址的不同,参数不同等方式来实现自动刷新的功能,想要刷新当前组件,只需执行:
refresh(){
this.$router.replace({
path:'/aboutus/index',
query:{
t:Date.now()
}
})
}
也可以借助中间组件,先跳转到中间组件,然后在中间组件中设置立即跳转回来,用户看到的效果就类似于刷新了当前页面。
另外还可以通过:location.reload()
this.$router.go(0)
1.修改app.vue
<template>
<div id="app">
<router-view v-if="isRouterAlive"></router-view>
</div>
</template>
<script>
export default{
name:'app',
provide(){
return {
reload:this.reload
}
},
data(){
return {
isRouterAlive:true
}
},
methods:{
reload(){
this.isRouterAlive = false;
this.$nextTick(()=>{
this.isRouterAlive = true;
})
}
}
}
</script>
2.依赖注入
在需要刷新的组件中,注入依赖:
export default{
inject:['reload'],
name:'xxx',
methods:{
getList(){
this.reload();//直接调用this.reload();实现依赖的使用
}
}
}