17.页面刷新的五种方式

1. 第一种(推荐)
缺点:这种方法会在浏览器地址栏中多添加#reloaded
  mounted() {
    if (location.href.indexOf("#reloaded") == -1) {
      location.href = location.href + "#reloaded";
      location.reload();
    }
  },

 

2. 第二种(简单粗暴)
缺点:相当于按ctrl+F5 强制刷新那种,整个页面重新加载,会出现一个瞬间的空白页面,体验不好
this.$router.go(0) //方式一
location.reload() //方式二

 

3. 第三种(新建一个空白页面,点击确定的时候先跳转到这个空白页,然后再立马跳转回来)
优点:适用于dialog关闭时刷新页面数据,不会出现一瞬间的空白页
缺点:只是地址栏有个快速的切换的过程
//监听dialog的关闭事件或者确定按钮的点击事件,当事件触发时执行下面代码
this.$router.replace({
  path: '/path1', //空白页的路由地址
  name: 'name1'
})

//在空白页面执行下面的代码
data(){
this.$router.replace({
  path: '/path2', //让路由跳转回当前页面
  name: 'name2'
})
return {}
}

 

4. 第四种(provide/inject组合)
步骤一:修改App.vue组件
<template>
  <div id="app">
    <transition>
      <router-view v-if="isRouterAlive" />
    </transition>
  </div>
</template>
<script>
export default {
  name: "App",
  provide() {
    return {
      reload: this.reload
    };
  },
  data() {
    return {
      isRouterAlive: true
    };
  },
  methods: {
    //通过声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载,这里定义了isRouterAlive=true/false来控制
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(function() {
        this.isRouterAlive = true;
      });
    }
  }
};
</script>

步骤二:在需要刷新的页面中注入App.vue组件提供reload 依赖,然后直接用this.reload来调用就行

<script>
export default {
  inject: ["reload"],
  name: "reload",

  data() {
    return {};
  },

  methods: {
    close() {
      this.reload();
    }
  }
};
</script>

 

5. 第五种(keep-alive)
方法:利用vue的内置组件keep-alive巧妙实现进入页面的时候重新获取想要的数据
<template>
  <div id="app">
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>
<script>
//使用Vue组件切换过程钩子activated(keep-alive组件激活时调用),而不是挂载钩子mounted
export default {
  activated: function() {//当页面被激活时触发
    this.getCaseDetail()
  }
 }
</script>

 

posted @ 2023-07-06 15:26  cjl2019  阅读(368)  评论(0编辑  收藏  举报