0👍
You can pass $event
object from your template and modify your makeIt
function as;
HTML:
@click="makeIt(i, $event)"
JS:
makeIt(hashbang, event) {
if (event.keyCode === 13) {
//do something
}
this.$router.push(`#${hashbang}`)
}
0👍
I’m not completely sure that triggering the Enter keypress is the right thing to do in order to scroll down to the desired section.
You might consider handling the scroll with VueScrollTo (you can find it here). Then it would be as easy as calling VueScrollTo.scrollTo()
from within the makeIt
method.
makeIt(hashbang) {
this.$router.push(`#${hashbang}`);
VueScrollTo.scrollTo(`.section-${hashbang}`, 500);
}
Here’s a working example of how I would do it: jsfiddle.
Then you might still want to push the index to the route, in order to get to the selected section when browsing to the exact URL.
Editing my answer to suggest a different approach:
Since you’re using VueRouter, you might take advantage of the hash property of routes and the scrollBehavior()
method when defining the router options. This way you could have something like this:
<router-link tag="li" v-for="i in 3" :key="i" :to="{ name: 'theRouteName', hash: '#section-' + i }">Link {{i}}</router-link>
This makes the $router.push()
part and the entire makeIt()
method unnecessary.
Also, you should add the scroll behavior to the router configuration:
const router = new VueRouter({
routes,
mode: "history",
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {˙
return savedPosition;
}
if (to.hash) {
return { selector: to.hash };
}
return { x: 0, y: 0 };
}
});
I saved a version of this solution on jsfiddle, you might want to try it on your sandbox or your local version of the app.