當我們在做項目時,我們需要做當前頁面的刷新來達到數據更新的目的,在此我們大概總結了幾種常用的頁面刷新的方法。
1.window.location.reload(),是原生JS提供的方法,this.$router.go(0):是vue路由里面的一種方法,這兩種方法都可以達到頁面刷新的目的,簡單粗暴,但是用戶體驗不好,相當于按F5刷新頁面,會有短暫的白屏,相當于頁面的重新載入。
2.通過路由跳轉的方法刷新,具體思路是點擊按鈕跳轉一個空白頁,然后再馬上跳回來:
當前頁面:
<template> <div> <el-button type="primary" class="btn" @click="btnaction">摁我刷新頁面</el-button> </div></template><script> export default{ data(){ return{ } }, mounted(){ }, methods:{ btnaction() {// location.reload()// this.$router.go(0) this.$router.replace({ path:'/empty', name:'empty' }) } } }</script>
空白頁面:
<template> <h1> 空頁面 </h1></template> <script> export default{ data() { return{ } }, created(){ this.$router.replace({ path:'/', name:'father' }) } }</script>
當點擊按鈕時地址欄會有快速的地址切換過程。
3.控制<router-view></router-view>的顯示與否,在全局組件注冊一個方法,該方法控制router-view的顯示與否,在子組件調用即可:
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(function() { this.isRouterAlive = true console.log('reload') }) } }}</script>
當前組件:
<template> <div> <el-button type="primary" class="btn" @click="btnaction">摁我刷新頁面</el-button> </div></template> <script> export default{ inject: ['reload'], // 引入方法 data(){ return{ } }, components:{ }, mounted(){ }, methods:{ btnaction() {// location.reload()// this.$router.go(0)// this.$router.replace({// path:'/empty',// name:'empty'// }) this.reload() // 調用方法 } } }</script>
當點擊按鈕時所有頁面重新渲染。
4.對列表操作后的表格刷新的操作方法:
當我們在操作數據表格時,會對表格進行增刪改查,做完操作我們需要對列表進行刷新來達到重新渲染,但是當如果存在分頁,我們在比如第3頁進行刪除操作,如果按照以往的刷新方法,刷新完后便進入了第一頁,這肯定不是我們想要的,這時候我們常用的做法是重新調用數據渲染方法,通常我們會有獲取數據接口,刪除接口等等,頁面加載時調用獲取數據的方法,當我們執行刪除操作時,再重新調用獲取數據的方法即可。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答