【无标题】

vue刷新当前页面

背景

在项目开发中遇到了需要刷新当前页面的场景。中途尝试了以下四种方法
1、this. f o r c e U p d a t e ( ) t h i s . forceUpdate() this. forceUpdate()this.forceUpdate() 是Vue.js中的一个方法,用于强制组件重新渲染,即使没有响应式数据发生变化。
2、 this.$router.go(0)
在history记录中前进或者后退val步,当val为0时刷新当前页面。
3、location.reload()
可以简单地实现当前页面的刷新,这个方法会重新加载当前页面,类似于用户点击浏览器的刷新按钮。
4、window.location.href = window.location.href
这个方法会重新加载当前URL所对应的页面,从而实现页面的刷新效果

具体使用如下

<button @click="refresh">刷新页面</button>
methods: {
  refresh() {
  //以下方法任选一种
 	 //方法1
    this.$forceUpdate();
    //方法2
    //this.$router.go(0);
    //方法3
    //location.reload();
    //方法4
    //window.location.href = window.location.href ;
  }
}

这些方法都会刷新整个页面,中间会出现明显的闪屏,体验感不是太好。
几经波折终于找到了一个之局部刷新的方法

用provide / inject 组合

原理:允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效
在App.vue,声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载。

<template>
  <div id="app">
    <router-view v-if="isRouterAlive"></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  provide () {
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      isRouterAlive: true
    }
  },
  methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    }
  }
}
</script>

在需要用到刷新的页面。在页面注入App.vue组件提供(provide)的 reload 依赖,在逻辑完成之后(删除或添加…),直接this.reload()调用,即可刷新当前页面。

注入reload方法在这里插入图片描述

methods: {
  refresh() {
  //以下方法任选一种
 	 //方法1
    //this.$forceUpdate();
    //方法2
    //this.$router.go(0);
    //方法3
    //location.reload();
    //方法4
    //window.location.href = window.location.href ;
    //方法5
    this.reload();
  }
}

相关推荐

  1. 标题

    2024-03-23 13:24:04       72 阅读
  2. 标题

    2024-03-23 13:24:04       69 阅读
  3. 标题

    2024-03-23 13:24:04       67 阅读
  4. 标题

    2024-03-23 13:24:04       77 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-23 13:24:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-23 13:24:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-23 13:24:04       87 阅读
  4. Python语言-面向对象

    2024-03-23 13:24:04       96 阅读

热门阅读

  1. js知识总结

    2024-03-23 13:24:04       38 阅读
  2. 多目标优化算法帕累托前沿的指标

    2024-03-23 13:24:04       37 阅读
  3. 前端需要掌握的 mysql 基础知识

    2024-03-23 13:24:04       41 阅读
  4. 数据结构与算法:选择排序与快速排序

    2024-03-23 13:24:04       38 阅读
  5. Redis中的常用数据结构

    2024-03-23 13:24:04       40 阅读
  6. C# 线程锁使用

    2024-03-23 13:24:04       43 阅读
  7. Android输入法相关(二)

    2024-03-23 13:24:04       44 阅读