[英]How can I add a URL param after a link is clicked in Vue js?
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.
我有来自 JSON 文件的数据,我想在单击它们时将标题添加到当前 url。
Let's say I have the headings(this is contained in my json object: headings.text
):假设我有标题(这包含在我的 json 对象中:
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.当用户单击Heading 1 时,我希望我当前的 URL
www.something.com
更改为www.something.com/Heading1
,其他标题也是如此。
How can I achieve this in Vue?我如何在 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 .您可以使用Vue Router 。 Namely, you can define a click event function and use Vue Router's programmatic navigation to navigate to the route you specify.
也就是说,您可以定义一个点击事件函数,并使用Vue Router 的编程导航来导航到您指定的路线。
<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.如果您希望根据
href
属性更改 url,则需要使用a
标记。
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:因此,与其将
href
添加到b-list-group-item
,还可以添加一个触发函数的点击事件:
<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)}`;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.