I have heading links on my sidebar that scrollspy on my main content and of course takes me to the referenced heading in the main content when I click on them. I have data coming from a JSON file and I would like to add the headings to the current url when they're clicked.
Let's say I have the headings(this is contained in my json object: headings.text
):
When the user clicks on Heading 1 , I want my current URL www.something.com
to change to www.something.com/Heading1
and likewise for the other headings.
How can I achieve this in Vue?
This is what I have so far.
<b-list-group-item :href="`#heading-${headingHash(headings.text)}`"> <--Heading reference.
<span>
<b>{{ index + 1 }}.</b> {{ headings.text }} <-- Heading itself.
</span>
</b-list-group-item>
Would appreciate some help. Thanks!
You can use Vue Router . Namely, you can define a click event function and use Vue Router's programmatic navigation to navigate to the route you specify.
<template>
<b-list-group-item
@click="handle(headings.text)"
:href="`#heading-${headingHash(headings.text)}`"
>
<span>
<b>{{ index + 1 }}.</b> {{ headings.text }}
</span>
</b-list-group-item>
</template>
<script>
export default {
methods: {
handle(heading) {
this.$router.push({
path: `Heading${heading}`
})
}
}
}
</script>
If you want the url to change based on a href
attribute, you need to use an a
tag.
Otherwise, you can do it programmatically. So, instead of adding href
to b-list-group-item
to could add a click event that would trigger a function:
<b-list-group-item @click"changeUrl(headings.text)">
And your method could be something like:
methods: {
changeUrl(text) {
window.location.href = `#heading-${this.headingHash(text)}`;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.