vue页面刷新 provide/inject|this.$router.replace|location.reload()

2,787 阅读1分钟

1、使用provide/inject方式

2、使用this.$router.replace

3、location.reload()

第一种方式:常用于整个页面刷新

  • provide:Object | () => Object
  • inject:Array | { [key: string]: string | Symbol | Object }

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

provide 和 inject 绑定并不是可响应的,然而,如果传了一个可监听的对象,那么其对象的属性还是可响应的。

要想做到页面刷新,只需在app.vue中定义provide,在其子孙组件的点击事件中刷新整个页面。

app.vue

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

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

子组件

export default{
    inject:['reload'],
    methods:{
        handleChange(){
            this.reload()
        }
    }
}

第二种方式:常用于路由切换

核心思想是重定向到一个空白页面,在返回当前页面,缺点是路由会变换两次

先建立redirect页面

export default {
  beforeCreate() {
    const { query } = this.$route
    const path = query.path
    this.$router.replace({ path: path })
  },
  mounted() {},
  render: function(h) {
    return h() // avoid warning message
  }
}

导航Item点击事件

clickLink(routePath){
    const fullPath = encodeURI(routePath)
    this.$router.replace({
        path: '/redirect',
        query: {
            path: encodeURI(fullPath)
        }
    })
}

还可解决其他页面刷新问题,比如网速慢的时候,你点击了生成某个列表,网速太慢你想去其他页面,在返回来的时候看到的可能不是最新数据,这时候你也可以使用此种方式,重新刷新页面,,,

第三种方式: 缺点就是会出现空白页面

简单粗暴
location.reload()