You can remember the position in a view and navigate users to that position when they click on ‘back’. You could also navigate users to specific anchor links in a long page.
Vue helps you to create a great single page application. Navigation between views is almost seamless and “feels” really fast. This magic of front-end routing is enabled by the Vue router.
A simple router code-fragment looks like this -
To navigate from one page to the other, you simply do -
This is good to navigate between the different pages of an application. But, what if you want to navigate to a specific anchor link?
To navigate to a specific link in a traditional HTML application, you use simple
<a id="footer"> to scroll to the footer. This works perfectly for home page or simple navigations, but not in all use cases in a Vue application using
router-link. Consider the below use-cases -
- user clicks on a link after reading 3/4th page of your beautifully written text
- user clicks on ‘back’ button
In each of these cases, the user lands on the beginning of the page in history - which is not a nice experience. Ideally they need to be navigated to the position that they were at previous to clicking on the super-clickable link.
You accomplish the above described navigation with two steps.
Step 1: Add
You simply add
router-link knows to navigate to a link and to a specific anchor element.
Step 2: Change router to scroll to position or anchors
Hash by itself will change the URL to include the specific anchor in URL. But -
- we need to scroll to the specific anchor
- we may also need to navigate to the previously remembered position if user comes to the page through
We address the requirement by scrolling to either the specified anchor or to the previously remembered position. We do this by changing the router.
Find the example code on Github.
Vue makes life real easy, doesn’t it?