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>
复制代码
相关文章
相关标签/搜索