vue如何实现页面刷新
目录
1.this.$router.go(0)
2.location.reload()
3.跳转空白页再回跳
4.控制的显示隐藏
5.搭配provide/inject使用。
6.通过中央事件总线bus进行通讯传值,监听操作,重新调用数据接口
实际业务交互中,进行交互操作后,可能需要刷新页面来重新获取数据
刷新页面方法如下:
1.this.$router.go(0)
缺点:类似F5刷新,会出现瞬间白屏,体验不好
2.location.reload()
缺点:与方法1类似
3.跳转空白页再回跳
在需要刷新的地方写上:
this.$router.push('/emptyPage')
跳转到空白页,在emptyPage.vue的beforeRouteEnter
钩子里控制页面跳转,从而达到刷新的效果
beforeRouteEnter (to, from, next) {
next(vm => {
vm.$router.replace(from.path)
})
}
缺点:能看到路由快速变化
4.控制的显示隐藏
默认
this.isRouterAlive = false
this.$nextTick(function () {
this.isRouterAlive = true
})
显示上无明显问题。
5.搭配provide/inject使用。
provide/inject是vue组件通讯的一种方式,其它vue通讯方法也可适当搭配使用。
1.在App.vue页面或别的上级页面中定义provide,返回一个对象的函数,函数处理路由v-if变量的更改,如方法4。代码如下:
<template>
<div id="app">
<router-view v-if="isRouterAlive" />
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
isRouterAlive: true
};
},
provide() {
return {
reload: this.reload
};
},
methods: {
reload() {
this.isRouterAlive = false;
this.$nextTick(() => {
this.isRouterAlive = true;
});
}
}
};
</script>
<style></style>
2.在需要刷新的页面引入依赖:inject: [‘reload’]
3.在需要执行的地方直接调用方法即可:this.reload()
6.通过中央事件总线bus进行通讯传值,监听操作,重新调用数据接口
1.main.js中给vue绑定bus
Vue.prototype.$bus = new Vue()
2.在组件的交互方法中使用$emit分发触发事件
this.$emit('change')//chang:自定义方法名
3.在调用组件的页面中使用$on监听change,并调用方法重载数据
mounted () {
this.$bus.$on('change', ()=> {
this.doSomething()//自定义获取数据方法,或调用方式4
})
}
还没有评论,来说两句吧...