在路由跳转时,会出现页面需要重新刷新一遍才能获取数据加载页面,这时添加一个监听器,如果跳转到页面刷新一次。
export default {
name: 'App',
provide(){
return{

reload:this.reload
}
},
data(){
return {

isRouterAlive:true,
}
},
//监听器
watch: {
// 方法1
'$route' (to, from) { //监听路由是否变化

// console.log(999)

if(to.path == "/"){ //跳转到哪个页面

location.reload()

}
},
},
methods:{
reload(){

this.isRouterAlive = false;

this.$nextTick(function () {

this.isRouterAlive = true

});
},
},
}
export default {
name: 'App',
provide(){
return{

reload:this.reload
}
},
data(){
return {

isRouterAlive:true,
}
},
//监听器
watch: {
// 方法1
'$route' (to, from) { //监听路由是否变化

// console.log(999)

if(to.path == "/"){ //跳转到哪个页面

location.reload()

}
},
},
methods:{
reload(){

this.isRouterAlive = false;

this.$nextTick(function () {

this.isRouterAlive = true

});
},
},
}补充知识:vue监听路由的改变和监听页面的刷新与离开补充知识:补充知识:vue监听路由的改变和监听页面的刷新与离开要分清两者的区别。首先是监听页面的刷新与离开,此时相当于直接在这个网页中按了刷新,如果是webapp则是离开这个app而不是切换路由!如果是用js的特性监测,则是不仅可以页面的刷新与离开,还能切换路由。注意当keepalive时即使切换了路由也无效。在script中直接增加监听器监视beforeunload:

//监视如果页面离开

created() {

window.addEventListener('beforeunload', this.updateHandler)

},

beforeDestroy() {

this.finalItemDetail(); // 自己要进行的操作

},

destroyed() {

window.removeEventListener('beforeunload', this.updateHandler)

},

//监视如果页面离开

created() {

window.addEventListener('beforeunload', this.updateHandler)

},

beforeDestroy() {

this.finalItemDetail(); // 自己要进行的操作

},

destroyed() {

window.removeEventListener('beforeunload', this.updateHandler)

},然后methods中添加finalItemDetail和updateHandler方法:

updateHandler() {

this.finalItemDetail()

},

finalItemDetail() {

console.log('刷新或关闭');

},

updateHandler() {

this.finalItemDetail()

},

finalItemDetail() {

console.log('刷新或关闭');

},如果想监听某个特定的页面的离开,比如我现在在/index下,现在去了/index/001下面,就可以在watch中监听路由的变化,前提是实用vue-router。如果是简单的判断路由变化可以用注释掉的,直接执行clear方法(自己定义在methods中)但是注意这个只能监听自己子路由的变化!

watch: {

// 如果路由有变化,会再次执行clear方法

// "$route": "clear",

$route(to , from){

console.log( to.path, from.path );

this.clear(to.path);

}

},

watch: {

// 如果路由有变化,会再次执行clear方法

// "$route": "clear",

$route(to , from){

console.log( to.path, from.path );

this.clear(to.path);

}

},然后我还额外做了个判断:

clear(path) {

if(path!="/item/item01/evaluate")

console.log("从这个页面离开了");

this. active=0;

},

clear(path) {

if(path!="/item/item01/evaluate")

console.log("从这个页面离开了");

this. active=0;

},以上这篇vue在App.vue文件中监听路由变化刷新页面操作就是小编分享给大家的全部内容了,希望能给大家一个参考。