I encountered a curious case during development.
I have a modal component that warns users about a change in price:
If a user clicks the button I want the page to reload and automatically run the onMounted hook, after that calculate a new price inside the hook with an apiCall.
The behavior I encountered is that nothing changes about the page and the modal remains open like it’s ignoring the router.push() method.
I wanted to implement this solution in Vue 3 and understand why router.push() doesn’t work.
I found a workaround with window.location.href but I’d love to hear the reason why using the standard router is not allowing me to succed with the standard vue-router.
I am inside the route /payment?code=123&hash=123, the object routerEnums.PAYMENT is equal to ‘/payment’, It works fine with any other route except this one.
/**script**/
import {useRouter} from "vue-router";
const router = useRouter();
/**template**/
<change-price-modal-good
v-if="showModalPriceChange"
@price-change-button-clicked="router.push(routerEnums.PAYMENT)"
/>
2
Answers
As the documentation says to router.push() "This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL. This is the method called internally when you click a tag router-link, so clicking router-link :to="…" is the equivalent of calling router.push(…).".
You can also put some properties to the router.push() as path or name, params, query, hash, etc.
If you want to reload a component use router.go(0). You can find more information on the link here.
If the reason behind the page reload is to run
onMounted
again, it can be achieved without reloading the whole app. You can set a key on the<router-view>
that renders the component withroute.fullPath
as value. On router push the key will change forcing the remount of the component.Also, you can use a computed key, and change it only for the desired route, returning a default key for the rest of the routes.