In the vue project, we need to refresh the page many times, for example, after the local user information is updated, or when we need to reload the data of the current page, using the window.location.reload() or window.history.go(0) method is to refresh the whole window. Like the h5 shortcut key, there will be a short blank, and the experience is very bad. Here are two kinds of senseless brushes used in the vue project New page method:
I. provide/inject method
The properties provide d by the parent component can be received by input in any child component. Then we can dynamically change the display and hide of the total route in the App page to achieve the refresh effect. Define a reload method on the App page:
App.vue
reload() { this.defaultActive = false; this.$nextTick(() => { this.defaultActive = true; }); }
defaulActive is used to control the development of the page:
<template> <div id="app"> <router-view v-if="defaultActive" /> </div> </template>
provide provides access to sub components:
provide() { return { reload: this.reload }; }
The global method is received through inject on the page to be refreshed:
page.vue
inject: ["reload"]
Call this method when refresh is needed:
refresh() { this.reload(); }
All codes:
App.vue:
<template> <div id="app"> <router-view v-if="defaultActive" /> </div> </template> <script> export default { provide() { return { reload: this.reload }; }, data() { return { defaultActive: true }; }, methods: { reload() { this.defaultActive = false; this.$nextTick(() => { this.defaultActive = true; }); } } }; </script>
page.vue
<script> export default { inject: ["reload"], data() { return {}; }, methods: { refresh() { this.reload(); } } }; </script>
2. Middle page redirection
You can create a new page reload.vue. When the page.vue needs to refresh, point the route to the reload page, and then jump back to the page page. Because the key of the page has changed, the page will be refreshed
page.vue:
refresh() { const { fullPath } = this.$route; this.$router.replace({ path: "/redirect", query: { path: fullPath } }); }
reload.vue:
<script> export default { name: "reload", props: {}, beforeCreate() { const { query } = this.$route; const { path } = query; this.$router.replace({ path: path }); }, render(h) { return h(); } }; </script>