vue刷新當前頁面

方案一

  • 利用v-if 來觸發組件從新渲染,達到刷新頁面的目的
// App.vue 組件
<template>
  <div id="app">
    // 2. isRouterAlive變化, router-view 從新渲染
    <router-view v-if="isRouterAlive"></router-view>
  </div>
</template>

<script>
export default {
  provide() {
    return {
      reload: this.reload
    };
  },
  data() {
    return {
      isRouterAlive: true
    };
  },
  methods: {
    reload() {
      // 1.子組件經過調用 reload 方法來觸發isRouterAlive值的變化
      this.isRouterAlive = false;
      this.$nextTick(function() {
        this.isRouterAlive = true;
      });
    }
  }
};
</script>
複製代碼
// children組件
<template>
  <div>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  data() {
    return {
      isReload: false
    };
  },
  methods: {
    _ajax() {
        setTimeout(() => {
            // isReload 開關值,避免某些場景下使用 reload() 出現死循環
            // 根據自身場景來肯定是否須要使用 isReload
            if(this.isReload) {
                // 須要刷新頁面時調用 reload 方法
                this.reload();
            }
        }, 3000)
    }
  }
};
</script>
複製代碼

方案二

  • 利用v-key的變化來觸發頁面更新
// App.vue
<template>
  <div id="app">
    // 2. activeDate變化, router-view 從新渲染
    <router-view :key="activeDate"></router-view>
  </div>
</template>

<script>
export default {
  provide() {
    return {
      reload: this.reload
    };
  },
  data() {
    return {
      activeDate: Date.now();
    };
  },
  methods: {
    reload() {
      // 1.子組件經過調用 reload 方法來觸發activeDate值的變化
      this.activeDate = Date.now();
    }
  }
};
</script>
複製代碼
// children組件
// 代碼與方案一相同
<template>
  <div>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  data() {
    return {
      isReload: false
    };
  },
  methods: {
    _ajax() {
        setTimeout(() => {
            if(this.isReload) {
                this.reload();
            }
        }, 3000)
    }
  }
};
</script>
複製代碼
相關文章
相關標籤/搜索