一、window.history.go()方法刷新上一頁
使用window.history.go()方法可以實現返回上一頁並且實時刷新頁面。這個方法是HTML5新增的API之一,可以讓我們控制瀏覽器的歷史紀錄,以及前進和後退的效果。在Vue中,我們可以通過監聽路由的變化來實現頁面的刷新。下面是示例代碼:
// 監聽路由
watch: {
$route(to, from) {
if(from.path === '/previousPage') {
window.history.go(0);
}
}
}
二、使用Bus實現
除了使用window.history.go()方法,我們還可以使用Bus來實現頁面的刷新。在父組件中註冊一個Bus,子組件就可以通過emit來觸發父組件中的方法,然後在方法中刷新頁面。下面是示例代碼:
// 父組件
import EventBus from '@/plugins/EventBus.js'
export default {
methods: {
refreshPage() {
window.location.reload();
}
},
mounted() {
EventBus.$on('refresh', () => {
this.refreshPage();
});
}
}
// 子組件
import EventBus from '@/plugins/EventBus.js'
export default {
methods: {
refreshPage() {
EventBus.$emit('refresh');
}
}
}
三、使用meta標籤禁用緩存
我們還可以通過使用meta標籤來禁用緩存,每次訪問頁面都會重新載入,達到刷新的效果。下面是示例代碼:
export default {
methods: {
goBack() {
window.history.go(-1);
}
},
mounted() {
// 禁用緩存
let head = document.getElementsByTagName('head')[0];
let meta = document.createElement('meta');
meta.setAttribute('http-equiv', 'Cache-Control');
meta.setAttribute('content', 'no-cache, no-store, must-revalidate');
meta.setAttribute('pragma', 'no-cache');
meta.setAttribute('expires', '0');
head.appendChild(meta);
}
}
四、使用location.reload()方法刷新
最後一種方法是使用location.reload()方法來實現頁面的實時刷新。這個方法會重新載入當前頁面,如果我們需要刷新上一頁,就需要在返回上一頁後再次使用location.reload()方法。示例代碼如下:
export default {
methods: {
goBack() {
window.history.go(-1);
location.reload();
}
}
}
總結
我們可以使用多種方法實現返回上一頁並且實時刷新頁面的效果。不同的方法適用於不同的場景,我們需要根據具體情況來選擇最合適的方法。在實際開發中,我們可以根據項目需求來選擇適合項目的方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/279757.html