[Vuejs]-How can I get the active element/currently viewed section's heading and display it (Bootstrap Vue ScrollSpy)?

1👍

The event listener documented in scrollspy’s documentation gives you the id of the currently active element. You can use it to display whatever you want.

I’ve put up a basic example here: https://codesandbox.io/s/competent-cherry-o4o6h?file=/src/App.vue

It’s basic because it queries $el to find the active element and get it’s innerHTML. Instead, in a real app, you could directly reference the object in the navigation which you used to render the navigation in the first place (and therefore avoid querying DOM).

To create this example, I only used code from the documentation, I added a computed property (getSectionTitle), and one optional feature: I noticed when scrolling to top there is no event emitted and I thought it would be good if I cleared the selected section (just as scrollspy no longer selects any element). So I added a scrollListener, in mounted, removed in beforeDestroy, which, when #nav-scorller scrolls to top, resets section to ''.
Other than that, it’s quite basic.

Again, this extra listener is not really necessary. I just thought it would be good to show how it could be done, to serve as an example for anyone who might need it in the future.

👤tao

Leave a comment