vue项目刷新当前页面最优解决方式

一般刷新页面可以用location.reload(true),history.go(0) 等方法,但是这对vue项目很不友好,会是页面重新加载,出现暂时性的空白,而且耗费性能,所以vue项目最好不用这些方法.vue有this.$forceUpdate()可以强制更新,下面介绍其他2种更好的方法.

方法一:带上当前页面路由跳转到一个重定向的页面,重定向页面再跳转回来. 

新建refresh.vue

  1.  
    <script>
  2.  
    export default {
  3.  
    name: "refresh",
  4.  
    beforeCreate(){
  5.  
    this.$router.push(this.$route.query.path)
  6.  
    },
  7.  
    };
  8.  
    </script>

router.js配置一个refresh路由

  1.  
    import refresh from './components/refresh.vue'
  2.  
     
  3.  
     
  4.  
    {
  5.  
    path: '/refresh',
  6.  
    name: 'refresh',
  7.  
    component: refresh
  8.  
    },

在要刷新的地方跳转传参即可

  1.  
    reflesh(){
  2.  
    this.$router.push({path:'/refresh',query:{path:this.$route.fullPath}})
  3.  
    },

方法二:通过v-if的功能触发页面刷新,结合provide和inject

修改app.vue,利用v-if可以刷新页面的属性,同时使用provide和inject将祖先节点的数据传递给子代节点

  1.  
    <template>
  2.  
    <div id="app">
  3.  
    <router-view v-if="isShow"></router-view>
  4.  
    </div>
  5.  
    </template>
  6.  
     
  7.  
    <script>
  8.  
    export default {
  9.  
    name: 'App',
  10.  
    provide () {
  11.  
    return {
  12.  
    reload: this.reload
  13.  
    }
  14.  
    },
  15.  
    data () {
  16.  
    return {
  17.  
    isShow: true
  18.  
    }
  19.  
    },
  20.  
    methods: {
  21.  
    reload () {
  22.  
    this.isShow= false
  23.  
    this.$nextTick(function () {
  24.  
    this.isShow= true
  25.  
    })
  26.  
    }
  27.  
    }
  28.  
    }
  29.  
    </script>

在要刷新的子路由页面引入inject,然后执行reload事件即可刷新页面

  1.  
    export default {
  2.  
    name: "demo",
  3.  
    inject:['reload'],
  4.  
    data() {
  5.  
    return {
  6.  
     
  7.  
    }
  8.  
    },
  9.  
    methods: {
  10.  
    reflesh(){
  11.  
    this.reload()
  12.  
    },
  13.  
    }
  14.  
    }

对比:

方法一有一个小问题是点击浏览器返回相当于没点击,因为跳转的是refresh页面,尔refresh又会跳回原页面.

方法二就没有上述问题,所以个人更推荐方法二

原文地址:https://www.cnblogs.com/qiunanyan/p/13929957.html