• Vue 实现页面刷新(provide 和 inject)


    Vue实现页面刷新

    普通方法:

      location.reload();

      this.$rotuer.go(0);

    这两个方法会强制刷新页面,出现短暂的空白闪烁

    使用 provide和inject

    这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。

    简单来说就是子孙组件可以访问到祖先的对象方法。

    在 App.vue 文件里写入 provide 的方法

    <!--页面级Vue组件-->
    <template>
        <div id="app">
            <keep-alive> 
                <router-view v-if="isRouterAlive"></router-view>
            </keep-alive>
        </div>
    </template>
    
    <script>
    export default {
      name: 'App',
      provide () {  // 在祖先组件中通过 provide 提供变量
        return {
          reload: this.reload  //  声明一个变量
        }
      },
      data () {
        return {
          isRouterAlive: true  // 控制 router-view 是否显示达到刷新效果
        }
      },
      methods: {
        // provide中声明的变量
        reload () {
          // 通过 this.isRouterAlive 控制 router-view 达到刷新效果
          this.isRouterAlive = false 
          this.$nextTick(function () {
            this.isRouterAlive = true
          })
        }
      }
    }
        
    </script>
    
    <style>
    </style>

    然后在需要刷新的子孙组件中用 inject 注入 App.vue 中声明的变量

    <template>
    <div class="page">
        <button @click="reloadFun">刷新</button>
    </div>
    </template>
    
    <script>
    import Vue from 'vue';
    
    export default {
        inject:['reload'], // 使用 inject 注入 reload 变量 
        data(){
            return{
    
            }
        },
        methods: {
            reloadFun(){
                this.reload();  // 直接使用
            }
          },
        
        mounted() {}
        
    }
    </script>
    
    <style>
    </style>
  • 相关阅读:
    csrf & xss
    android_sqlite
    android_error
    oracle笔记
    android_lesson_1
    mysql 设置编码
    前端进阶Event
    前端进阶Position
    chrome插件开发资料
    dom4j selectNodes
  • 原文地址:https://www.cnblogs.com/sanyekui/p/12698773.html
Copyright © 2020-2023  润新知