vue刷新页面之——provide来提供变量和inject来注入变量,以及该变量reload的使用

一、在App.vue 中,通过provide来提供变量

vue 刷新页面,父组件中通过provide来提供变量,在子组件中通过inject来注入变量。

<template>
  <div id="app">
    <router-view v-if="isRouterAlive"></router-view>
  </div>
</template>
<script>
export default {
    
    
  name: "App",
  provide() {
    
      // 1. 通过provide提供变量,注意要写成方法格式。this.reload是定义在methods中的reload方法
    return {
    
     reload: this.reload };
  },
  data() {
    
    
    return {
    
    
      isRouterAlive: true  // 2. 定义变量 ,控制 router-view ,达到刷新效果
    };
  },
  methods: {
    
    
    reload() {
    
      // 3. 控制 router-view, 达到刷新效果
      this.isRouterAlive = false;
      this.$nextTick(function() {
    
    
        this.isRouterAlive = true;
      });
    }
  }
};
</script>

二、在test.vue组件 中,通过inject来注入变量,并使用

<template>
  <div class="test">
    <h2 >数据显示</h2>
    <el-button @click="handleReload">点击刷新</el-button>
  </div>
</template>
<script>
  export default {
    
    
    inject:['reload'], // 注入reload变量
    methods:{
    
    
      handleReload(){
    
    
        this.reload(); //在这里可直接调用 ,一般用在新增一条数据,或者删除了一条数据,需要刷新当前页面的时候
      }
    }
  }
</script>

三、 用他们的原因

  1. 使用 window.reload()router.go(0) 刷新时,整个页面都会重新加载,用户体验不好。
  2. this.$router.push(this.$route.path);vue-router 重新跳转到当前路由,页面数据不刷新。(如调后台给表格中新增了一条数据,成功,但在此时页面的表格中是没有这条数据的)
  3. 使用场景:新增、删除数据等操作,调完后台需要对页面进行刷新,保证数据正确显示。

猜你喜欢

转载自blog.csdn.net/ddx2019/article/details/107819099
今日推荐