当 link 单击并重定向时,如何添加 class 活动?

How can I add class active when a link clicked and redirect?

我的vue组件是这样的:

<template>
    <div>
        ...
        <div class="list-group">
            <a :href="baseUrl+'/message/inbox'" class="list-group-item">
                Message
            </a>
            <a :href="baseUrl+'/message/review'" class="list-group-item">
                Review
            </a>
            <a :href="baseUrl+'/message/resolution'" class="list-group-item">
                Resolution
            </a>
        </div>
        ...
    </div>
</template>
<script>
    export default {
        ...
        data() {
            return {
                baseUrl: window.Laravel.baseUrl
            }
        },
        ...
    }
</script>

当link被点击时,它会调用url,我想在重新加载页面后在被点击的link上添加class active。

但是,我还是一头雾水,我该怎么做?

您可以添加计算的 属性,例如 currentPath:

computed: {
  currentPath () {
    // grab current url and return the part after `baseUrl `
    // e.g. '/message/inbox' or '/message/review'
    return '/message/inbox'
  }
}

还有一个 CSS class 适合您的特殊风格:

.active-item {
  /* key-value pairs here */
}

然后在您的模板中,您可以将 class 应用于匹配项:

<a :href="baseUrl+'/message/inbox'"
   :class="{ 'active-item': currentPath === '/message/inbox'}">
   class="list-group-item">Message</a>
<a :href="baseUrl+'/message/review'"
   :class="{ 'active-item': currentPath === '/message/review'}">
   class="list-group-item">Review</a>

请阅读 binding HTML classes with object syntax

上的文档

添加到 Leo 的回答中,引入一个自动检测是否处于活动状态的组件是个好主意,这样您就不需要编写一堆 <a> 元素和许多重复的属性。

例如 <custom-link> 组件:

<custom-link href="/message/inbox" class="list-group-item">
  Message
</custom-link>
<custom-link href="/message/review" class="list-group-item">
  Review
</custom-link>
<custom-link href="/message/resolution" class="list-group-item">
  Resolution
</custom-link>

如果你不需要在其他组件中复用这个组件或者list-group-item总是需要class,你也可以把这个class封装到<custom-link>.它看起来会更干净:

<custom-link href="/message/inbox">Message</custom-link>
<custom-link href="/message/review">Review</custom-link>
<custom-link href="/message/resolution">Resolution</custom-link>

custom-link 的代码如下所示:

<a
  :href="baseUrl + href"
  :class="{ active: isActive }"
  class="list-group-item"
>
  <slot></slot>
</a>

{
  props: ['href'],
  data: () => ({ baseUrl: window.Laravel.baseUrl }),
  computed: {
    isActive () {
      return location.href === this.baseUrl + this.href
    }
  }
}

我这里直接用location.href,如果你需要一些计算得到当前的URL,你也可以像Leo的例子一样使用计算的属性。