vue-router 刷新當前路由

因爲router-view是複用的,單純的改變id號並不會刷新router-viewvue

因此咱們能夠使用 watch 來監聽路由的變化,而後先push一個空路由,再返回上一頁,以下代碼:api

watch:{
        '$route': function (to, from) {
            let NewPage = '_empty' + '?time=' + new Date().getTime()/1000 //定義一個空頁面
            this.$router.push(NewPage)
            this.$router.go(-1) // 返回上一個頁面
        }  
    },

 還有另一種方法,是從知友那找到的:(https://www.zhihu.com/question/49863095/answer/289157209)ide

利用v-if控制router-view,在路由容器組件,如APP.vue中實現一個刷新方法this

一、用provide / inject來傳遞reload 在APP.vue裏定義spa

<template>
  <router-view v-if="isRouterAlive"/> //路由作判斷
</template>
<script>
export default {
 provide () { //父組件傳值
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      isRouterAlive: true
    }
  },
  methods: {
    reload () { //定義更新方法
      this.isRouterAlive = false
      this.$nextTick(() => (this.isRouterAlive = true))
    }
  }
}
</script>
在子組件中調用

inject: ['reload'], //子組件接受值 watch:{   '$route': function (to, from) {   this.reload() // 監測到路由發生變化時調用   } },
相關文章
相關標籤/搜索