vue 單頁面重載(刷新)

首先先說一下標題,此處的重新(刷新)並不是瀏覽器 reload ,只是當前頁面組件重新 create

最近重構的項目中有重新加載的按鈕,以前直接是 location.reload() ,但現在重構爲了單頁面方式,這個在 location.reload() 的話那體驗就太 low 了,剛好前段時間看了花褲衩大佬的 手摸手,帶你用vue擼後臺 系列五(v4.0新版本) ,仔細思考之後不得不說這個方法很贊,巧妙的將離開頁面的所有參數信息與 redirect 頁面信息結合,並且在 redirect 頁面信息中可以獲得之前頁面的信息,在 redirect 頁面的 created生命週期函數中再替換爲離開頁面的信息參數,離開的頁面經歷了 destroyedcreated 等其他生命週期,相當於重載了。

代碼如下:

// router.js
const router = new Router({
  ...
  routes: [
    ...
    {
      // 刷新頁面
      path: "/redirect/:path*",
      name: "redirect",
      component: () => import('./views/redirectPage/index.vue')
    }
    ...
  ]
  ...
})

需要在 views/redirectPage 文件夾下新建 index.vue ,內容如下:

<script>
export default {
  name: 'RedirectPage',
  created () {
    const { params, query } = this.$route
    const { path } = params
    this.$router.replace({ path: `/${path}`, query })
  },
  render (h) {
    return h()
  }
}
</script>

準備工作已經做好,使用的時候如下:

...
pageReload () {
  // 刷新
  this.$router.replace({ path: `/redirect${this.$route.fullPath}` })
}
...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章