在Vue js中单击链接后,如何添加URL参数?

时间:2020-01-06 08:05:57

标签: javascript vue.js url vuejs2

我的侧边栏上有标题链接,可滚动浏览我的主要内容,当我单击它们时,当然会将我带到主要内容中的引用标题。我有来自JSON文件的数据,我想在单击它们时将标题添加到当前url中。

假设我有标题(包含在我的json对象中:headings.text):

  1. 标题1
  2. 标题2
  3. 标题4

当用户单击标题1 时,我希望当前的URL www.something.com更改为www.something.com/Heading1,其他标题也是如此。

如何在Vue中实现这一目标?

这是我到目前为止所拥有的。

   <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>

感谢您的帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用Vue Router。即,您可以定义点击事件功能,并使用Vue Router's programmatic navigation导航到您指定的路线。

<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>

答案 1 :(得分:0)

如果您希望基于href属性更改网址,则需要使用a标签。

否则,您可以通过编程方式进行。因此,与其将href添加到b-list-group-item而不是添加可以触发功能的点击事件:

<b-list-group-item @click"changeUrl(headings.text)">

您的方法可能类似于:

methods: {
    changeUrl(text) {
      window.location.href = `#heading-${this.headingHash(text)}`;
    }
}