问题原因
Vue路由切换实际是组件间的切换,引用相同组件的时候,页面就无法更新
解决方案
方案1.watch监听路由参数变化,并重新渲染(谨慎选择)
该可以实现页面重新加载数据效果,但会出现页面单独刷新出错,滚动条没有返回顶部问题,根据业务需要选择此解决方法
方案2. provide和inject结合使用(推荐使用)
实现思路:在app.vue目录下,对<router-view></router-view>进行摧毁和重建(通过变量routerAlive的状态控制),页面会进行重新渲染。
下面是方案2的具体实现:
// app.vue
<template>
<div id="app">
<transition name="on" mode="out-in">
<router-view v-if="routerAlive" />
</transition>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
routerAlive: true
}
},
provide() {
return {
routerRefresh: this.routerRefresh
}
},
mounted() {
// 路由跳转后回到视图顶部
this.$router.afterEach((to, from, next) => {
window.scrollTo(0, 0)
})
},
methods: {
routerRefresh() {
this.routerAlive = false
this.$nextTick(() => {
this.routerAlive = true
})
},
}
}
</script>
// page.vue
export default {
inject:['routerRefresh'], // 注入
},
methods: {
// 跳转方法里面使用
linkGo() {
this.$router.push({path: '/'}, this.routerRefresh())
}
}
阅读进度 0%
private note
交流
文章暂不开放公开评论。如果你有想法、问题或建议,欢迎私下联系站长。
联系站长 →