vue reload当前页面

593 阅读1分钟

引言

做后台的时候难免会遇到需要重新加载当前页面去更新数据的方式。一般会采用window.reload()或者router.go(0)来达到刷新重加载的目的。但是这样整个浏览器就会进行重新加载,闪烁,对于用户体验来说并不是那么好。但是如果用vue-router重新路由到当前页面,就可以不用刷新页面了!!

方法

使用vue提供的provide/inject文档说明)从祖先组件向其所有子孙后代注入一个reload依赖

具体代码

// home.vue 

 <router-view  v-if="isRouterAlive"></router-view>

export default{
    data () {
        return  {
            isRouterAlive: true
        }
    },
    methods: {
        reload () {
            this.isRouterAlive = false
            this.$nextTick(() => {
                this.isRouterAlive = true
            })
        }
    },
    provide () {
        return {
            reload: this.reload
        }
    }
}

子组件

child.vue
export default{
    inject: ['reload'] // 注入reload
    methods: {
        test () {
            this.reload() // 直接调用reload方法
        }
    }
}