vue刷新当前页面

1,930 阅读1分钟

方案一

  • 利用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>