vue使用provide/inject方式解决刷新当前页面问题

2021-04-07 22:14:27
679次阅读
0个评论
当用户进行操作后需要刷新当前局部的页面时,如果使用

location.reload();




this.$router.go(0);


这2种刷新,原理分别是F5类刷新以及跳转至当前页面的刷新,虽然也能刷新,但是会造成当前全部页面刷新。如果用户网络不好时,就会出现空白页面的情况。

所以我们需要一种全新的页面刷新方式,局部刷新页面

1.我们先在APP.vue中使添加下列代码


<template>
    <div id="app">
    	<router-view v-if="isRouterAlive"></router-view>
	</div>
</template>
<script>
    export default {
        name: 'App',
        provide () {    //父组件中通过provide来提供变量,在子组件中通过inject来注入变量。                                             
            return {
                reload: this.reload                                              
            }
        },
        data() {
            return{
                isRouterAlive: true                    //控制视图是否显示的变量
            }
        },
        methods: {
            reload () {
                this.isRouterAlive = false;            //先关闭,
                this.$nextTick(function () {
                    this.isRouterAlive = true;         //再打开
                }) 
            }
        },
    }
</script>

2.在我们需要刷新的局部页面中添加如下代码

export default {
  inject:['reload'], //注入reload方法
  data() {
	return{
	}
}

在需要实现刷新页面时添加

this.reload();


这样就可以了。

例如

<template>
    <div>
          <el-table
            :data="tableData"
            style="width: 100%">
            <el-table-column
              prop="id"
              label="编号"
              width="400">
            </el-table-column>
            <el-table-column
              prop="name"
              label="name"
              width="400">
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="180">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleClick(scope.row)">刷新</el-button>
              </template>
            </el-table-column>
          </el-table>
    </div>
</template>
<script>

export default {

    inject:['reload'], 

    data() {
    return {
        tableData:[{
        }],
    }
    },
      created(){
    this.$axios.get("category/findAll").then((res)=>{	//调用一个借口,baseURL在其他页面封装过的
    
        this.tableData=res.data.data;        
    }) 
    },
    methods:{
      handleClick:function(res){
        this.reload();
      }
    },
}
</script>

<style scoped>

</style>




收藏00

登录 后评论。没有帐号? 注册 一个。