vue-cli项目中如何实现局部页面的刷新?

功能需求讲解:
  在vue-cli项目中,通常会去刷新页面,一般我们比较暴力的刷新页面的方法为location. reload(),直接将整个页面进行了刷新,

这种方法虽然也达到了效果,但是用户体验却不是很好,我们要的效果只是将当前页面进行刷新。

这里推荐使用provide / inject 组合的方法来进行局部页面来进行刷新

具体实现步骤如下:
一、在App.vue页面中定义刷新的方法

二、在使用的页面中进行调用

具体代码如下

App.vue代码

<template>
  <div id="app">
    <router-view v-if="isRouterAlive"/>
  </div>
</template>

<script>
export default {
  name: 'App',
  provide () {
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      isRouterAlive: true
    }
  },
  mounted () {

  },
  methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    }
  }
}
</script>

使用的子页面代码

<template>
  <div class="shop">
      <button @click="re">123</button>
  </div>
</template>

<script>
export default {
  name: 'shop',
  inject: ['reload'],
  data () {
    return {

    }
  },
  mounted () {
    console.log('重新加载了当前页面')
  },
  methods: {
    re () {
      this.reload()
    }
  }
}
</script>

这样就实现了局部刷新页面的效果,可以在定义的方法中加入加载动画,增强用户体验。

原文地址:https://www.cnblogs.com/qiuchuanji/p/10387022.html