scenario
Recently, in the process of project development, the customer raised a requirement: “When clicking the corresponding menu of the current page, the page can also be refreshed.”
Since the routing mechanism of the Vue project is the same, the corresponding components are not re-rendered. So clicking the menu repeatedly won’t change the route, and then the page won’t refresh.
Train of thought
Since the Vue routing mechanism cannot be changed, you have to look elsewhere. There are probably two ideas:
Scheme 1: Change the route
Plan 2: Use redirection
implementation
Scheme 1: Change the route
When switching routes, time stamps are added to the route and view changes are triggered by constantly changing the QUERY of the URL with each click.
// Implement menu refresh through timestamp
this.$router.push({
path: url,
query: {
t: +new Date(a)// Make sure that the query entry is different every time you click the route. Make sure that the view is refreshed}})Copy the code
Disadvantages: After each click, there is a long time stamp behind the address bar.
Plan 2: Use redirection
Using an empty Redirect page, determine whether the current route is the same as the clicked route. If so, redirect to the redirect page and then redirect back to the redirect page. This is the page refresh.
- Create an empty page:
src/layout/components/redirect.vue
<script>
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}}</script>
Copy the code
- Mount route:
src/router/index.js
{
path: '/redirect'.component: () = > import('@/layout/components/redirect.vue')},Copy the code
- Add the event where the menu jumps, for related processing:
<el-menu ... @select="selectMenuItem">
// ...
</el-menu>
<script>
export default {
methods: {
selectMenuItem (url, indexPath) {
if (this.$route.fullPath === url) {
// Click to manually redirect the current route to the '/redirect' page
this.$router.replace({
path: '/redirect'.query: {
path: encodeURI(url)
}
})
} else {
// Normal jump
this.$router.push({
path: url
})
}
}
}
}
</script>
Copy the code
The ending summarizes
Plan 1 is only half a page refresh. Scheme 2, which IS adopted in my current project, is more flexible than scheme 1 and can realize real page (component) refresh.
In this way, when clicking on the same menu, the address bar changes from: http://localhost:8080/#/redirect? Path = XXXXXX to http://localhost:8080/#/xxxxxx