Vue reloads/refreshes the current page and changes the url parameter to trigger the page life cycle

In the actual development of vue pages, it is often necessary to change the url parameters and reload the page data, but only changing the page url will not trigger the life cycle of the component, which requires other methods to achieve.

1. this.$router.go(0) and location.reload()

It is equivalent to refreshing the browser, which will reload the page resources, and the experience is quite poor.

2. Recommended use: provide / inject combination

In the index.vue (related to the page structure) file, declare the reload method to control the display or hiding of router-view, thereby controlling the reloading of the page.

<template>
  <div>
    <menu-top></menu-top>
    <menu-slide></menu-slide>
    <div class="app-content">
        <transition name="router-fades" mode="out-in">
            <router-view v-if="isRefresh"></router-view>
        </transition>
    </div>
  </div>
</template>
 
<script>
import MenuTop from "@/components/menu-top.vue";
import MenuSlide from "@/components/menu-slide.vue";
export default {
  provide () { //注入重新加载组件方法(子页面可以通过inject属性接收)
    return {
      reload: this.reload 
    }
  },
  components: {
    MenuSlide,
    MenuTop
  },
  data () {
    return {
      isRefresh: true
    }
  },
  methods: {
    async reload () {
      this.isRefresh= false
      await this.$nextTick()
      this.isRefresh= true
    }
  }
}
</script>

Principle: Allow an ancestor component to inject a dependency to all its descendants, no matter how deep the component hierarchy is, and it will always take effect when the upstream and downstream relationships are established

In the subpage that needs to be used, receive it through the inject attribute, call this.reload() directly, only load the current component, and trigger the life cycle function of the component, without refreshing the entire website, the effect is very good

<template>
    <div></div>
</template>

<script>
    export default {
        inject: ['reload'],
        methods:{
            reloadFun () {
                this.reload()
            }
        }
    }
</script>

Guess you like

Origin blog.csdn.net/weixin_39823006/article/details/130846693